iommu.c 109 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099
  1. // SPDX-License-Identifier: GPL-2.0-only
  2. /*
  3. * Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
  4. * Author: Joerg Roedel <jroedel@suse.de>
  5. */
  6. #define pr_fmt(fmt) "iommu: " fmt
  7. #include <linux/amba/bus.h>
  8. #include <linux/device.h>
  9. #include <linux/kernel.h>
  10. #include <linux/bits.h>
  11. #include <linux/bug.h>
  12. #include <linux/types.h>
  13. #include <linux/init.h>
  14. #include <linux/export.h>
  15. #include <linux/slab.h>
  16. #include <linux/errno.h>
  17. #include <linux/host1x_context_bus.h>
  18. #include <linux/iommu.h>
  19. #include <linux/iommufd.h>
  20. #include <linux/idr.h>
  21. #include <linux/err.h>
  22. #include <linux/pci.h>
  23. #include <linux/pci-ats.h>
  24. #include <linux/bitops.h>
  25. #include <linux/platform_device.h>
  26. #include <linux/property.h>
  27. #include <linux/fsl/mc.h>
  28. #include <linux/module.h>
  29. #include <linux/cc_platform.h>
  30. #include <linux/cdx/cdx_bus.h>
  31. #include <trace/events/iommu.h>
  32. #include <linux/sched/mm.h>
  33. #include <linux/msi.h>
  34. #include <uapi/linux/iommufd.h>
  35. #include "dma-iommu.h"
  36. #include "iommu-priv.h"
  37. static struct kset *iommu_group_kset;
  38. static DEFINE_IDA(iommu_group_ida);
  39. static DEFINE_IDA(iommu_global_pasid_ida);
  40. static unsigned int iommu_def_domain_type __read_mostly;
  41. static bool iommu_dma_strict __read_mostly = IS_ENABLED(CONFIG_IOMMU_DEFAULT_DMA_STRICT);
  42. static u32 iommu_cmd_line __read_mostly;
  43. /* Tags used with xa_tag_pointer() in group->pasid_array */
  44. enum { IOMMU_PASID_ARRAY_DOMAIN = 0, IOMMU_PASID_ARRAY_HANDLE = 1 };
  45. struct iommu_group {
  46. struct kobject kobj;
  47. struct kobject *devices_kobj;
  48. struct list_head devices;
  49. struct xarray pasid_array;
  50. struct mutex mutex;
  51. void *iommu_data;
  52. void (*iommu_data_release)(void *iommu_data);
  53. char *name;
  54. int id;
  55. struct iommu_domain *default_domain;
  56. struct iommu_domain *blocking_domain;
  57. /*
  58. * During a group device reset, @resetting_domain points to the physical
  59. * domain, while @domain points to the attached domain before the reset.
  60. */
  61. struct iommu_domain *resetting_domain;
  62. struct iommu_domain *domain;
  63. struct list_head entry;
  64. unsigned int owner_cnt;
  65. void *owner;
  66. };
  67. struct group_device {
  68. struct list_head list;
  69. struct device *dev;
  70. char *name;
  71. };
  72. /* Iterate over each struct group_device in a struct iommu_group */
  73. #define for_each_group_device(group, pos) \
  74. list_for_each_entry(pos, &(group)->devices, list)
  75. struct iommu_group_attribute {
  76. struct attribute attr;
  77. ssize_t (*show)(struct iommu_group *group, char *buf);
  78. ssize_t (*store)(struct iommu_group *group,
  79. const char *buf, size_t count);
  80. };
  81. static const char * const iommu_group_resv_type_string[] = {
  82. [IOMMU_RESV_DIRECT] = "direct",
  83. [IOMMU_RESV_DIRECT_RELAXABLE] = "direct-relaxable",
  84. [IOMMU_RESV_RESERVED] = "reserved",
  85. [IOMMU_RESV_MSI] = "msi",
  86. [IOMMU_RESV_SW_MSI] = "msi",
  87. };
  88. #define IOMMU_CMD_LINE_DMA_API BIT(0)
  89. #define IOMMU_CMD_LINE_STRICT BIT(1)
  90. static int bus_iommu_probe(const struct bus_type *bus);
  91. static int iommu_bus_notifier(struct notifier_block *nb,
  92. unsigned long action, void *data);
  93. static void iommu_release_device(struct device *dev);
  94. static int __iommu_attach_device(struct iommu_domain *domain,
  95. struct device *dev, struct iommu_domain *old);
  96. static int __iommu_attach_group(struct iommu_domain *domain,
  97. struct iommu_group *group);
  98. static struct iommu_domain *__iommu_paging_domain_alloc_flags(struct device *dev,
  99. unsigned int type,
  100. unsigned int flags);
  101. enum {
  102. IOMMU_SET_DOMAIN_MUST_SUCCEED = 1 << 0,
  103. };
  104. static int __iommu_device_set_domain(struct iommu_group *group,
  105. struct device *dev,
  106. struct iommu_domain *new_domain,
  107. struct iommu_domain *old_domain,
  108. unsigned int flags);
  109. static int __iommu_group_set_domain_internal(struct iommu_group *group,
  110. struct iommu_domain *new_domain,
  111. unsigned int flags);
  112. static int __iommu_group_set_domain(struct iommu_group *group,
  113. struct iommu_domain *new_domain)
  114. {
  115. return __iommu_group_set_domain_internal(group, new_domain, 0);
  116. }
  117. static void __iommu_group_set_domain_nofail(struct iommu_group *group,
  118. struct iommu_domain *new_domain)
  119. {
  120. WARN_ON(__iommu_group_set_domain_internal(
  121. group, new_domain, IOMMU_SET_DOMAIN_MUST_SUCCEED));
  122. }
  123. static int iommu_setup_default_domain(struct iommu_group *group,
  124. int target_type);
  125. static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
  126. struct device *dev);
  127. static ssize_t iommu_group_store_type(struct iommu_group *group,
  128. const char *buf, size_t count);
  129. static struct group_device *iommu_group_alloc_device(struct iommu_group *group,
  130. struct device *dev);
  131. static void __iommu_group_free_device(struct iommu_group *group,
  132. struct group_device *grp_dev);
  133. static void iommu_domain_init(struct iommu_domain *domain, unsigned int type,
  134. const struct iommu_ops *ops);
  135. #define IOMMU_GROUP_ATTR(_name, _mode, _show, _store) \
  136. struct iommu_group_attribute iommu_group_attr_##_name = \
  137. __ATTR(_name, _mode, _show, _store)
  138. #define to_iommu_group_attr(_attr) \
  139. container_of(_attr, struct iommu_group_attribute, attr)
  140. #define to_iommu_group(_kobj) \
  141. container_of(_kobj, struct iommu_group, kobj)
  142. static LIST_HEAD(iommu_device_list);
  143. static DEFINE_SPINLOCK(iommu_device_lock);
  144. static const struct bus_type * const iommu_buses[] = {
  145. &platform_bus_type,
  146. #ifdef CONFIG_PCI
  147. &pci_bus_type,
  148. #endif
  149. #ifdef CONFIG_ARM_AMBA
  150. &amba_bustype,
  151. #endif
  152. #ifdef CONFIG_FSL_MC_BUS
  153. &fsl_mc_bus_type,
  154. #endif
  155. #ifdef CONFIG_TEGRA_HOST1X_CONTEXT_BUS
  156. &host1x_context_device_bus_type,
  157. #endif
  158. #ifdef CONFIG_CDX_BUS
  159. &cdx_bus_type,
  160. #endif
  161. };
  162. /*
  163. * Use a function instead of an array here because the domain-type is a
  164. * bit-field, so an array would waste memory.
  165. */
  166. static const char *iommu_domain_type_str(unsigned int t)
  167. {
  168. switch (t) {
  169. case IOMMU_DOMAIN_BLOCKED:
  170. return "Blocked";
  171. case IOMMU_DOMAIN_IDENTITY:
  172. return "Passthrough";
  173. case IOMMU_DOMAIN_UNMANAGED:
  174. return "Unmanaged";
  175. case IOMMU_DOMAIN_DMA:
  176. case IOMMU_DOMAIN_DMA_FQ:
  177. return "Translated";
  178. case IOMMU_DOMAIN_PLATFORM:
  179. return "Platform";
  180. default:
  181. return "Unknown";
  182. }
  183. }
  184. static int __init iommu_subsys_init(void)
  185. {
  186. struct notifier_block *nb;
  187. if (!(iommu_cmd_line & IOMMU_CMD_LINE_DMA_API)) {
  188. if (IS_ENABLED(CONFIG_IOMMU_DEFAULT_PASSTHROUGH))
  189. iommu_set_default_passthrough(false);
  190. else
  191. iommu_set_default_translated(false);
  192. if (iommu_default_passthrough() && cc_platform_has(CC_ATTR_MEM_ENCRYPT)) {
  193. pr_info("Memory encryption detected - Disabling default IOMMU Passthrough\n");
  194. iommu_set_default_translated(false);
  195. }
  196. }
  197. if (!iommu_default_passthrough() && !iommu_dma_strict)
  198. iommu_def_domain_type = IOMMU_DOMAIN_DMA_FQ;
  199. pr_info("Default domain type: %s%s\n",
  200. iommu_domain_type_str(iommu_def_domain_type),
  201. (iommu_cmd_line & IOMMU_CMD_LINE_DMA_API) ?
  202. " (set via kernel command line)" : "");
  203. if (!iommu_default_passthrough())
  204. pr_info("DMA domain TLB invalidation policy: %s mode%s\n",
  205. iommu_dma_strict ? "strict" : "lazy",
  206. (iommu_cmd_line & IOMMU_CMD_LINE_STRICT) ?
  207. " (set via kernel command line)" : "");
  208. nb = kzalloc_objs(*nb, ARRAY_SIZE(iommu_buses));
  209. if (!nb)
  210. return -ENOMEM;
  211. iommu_debug_init();
  212. for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++) {
  213. nb[i].notifier_call = iommu_bus_notifier;
  214. bus_register_notifier(iommu_buses[i], &nb[i]);
  215. }
  216. return 0;
  217. }
  218. subsys_initcall(iommu_subsys_init);
  219. static int remove_iommu_group(struct device *dev, void *data)
  220. {
  221. if (dev->iommu && dev->iommu->iommu_dev == data)
  222. iommu_release_device(dev);
  223. return 0;
  224. }
  225. /**
  226. * iommu_device_register() - Register an IOMMU hardware instance
  227. * @iommu: IOMMU handle for the instance
  228. * @ops: IOMMU ops to associate with the instance
  229. * @hwdev: (optional) actual instance device, used for fwnode lookup
  230. *
  231. * Return: 0 on success, or an error.
  232. */
  233. int iommu_device_register(struct iommu_device *iommu,
  234. const struct iommu_ops *ops, struct device *hwdev)
  235. {
  236. int err = 0;
  237. /* We need to be able to take module references appropriately */
  238. if (WARN_ON(is_module_address((unsigned long)ops) && !ops->owner))
  239. return -EINVAL;
  240. iommu->ops = ops;
  241. if (hwdev)
  242. iommu->fwnode = dev_fwnode(hwdev);
  243. spin_lock(&iommu_device_lock);
  244. list_add_tail(&iommu->list, &iommu_device_list);
  245. spin_unlock(&iommu_device_lock);
  246. for (int i = 0; i < ARRAY_SIZE(iommu_buses) && !err; i++)
  247. err = bus_iommu_probe(iommu_buses[i]);
  248. if (err)
  249. iommu_device_unregister(iommu);
  250. else
  251. WRITE_ONCE(iommu->ready, true);
  252. return err;
  253. }
  254. EXPORT_SYMBOL_GPL(iommu_device_register);
  255. void iommu_device_unregister(struct iommu_device *iommu)
  256. {
  257. for (int i = 0; i < ARRAY_SIZE(iommu_buses); i++)
  258. bus_for_each_dev(iommu_buses[i], NULL, iommu, remove_iommu_group);
  259. spin_lock(&iommu_device_lock);
  260. list_del(&iommu->list);
  261. spin_unlock(&iommu_device_lock);
  262. /* Pairs with the alloc in generic_single_device_group() */
  263. iommu_group_put(iommu->singleton_group);
  264. iommu->singleton_group = NULL;
  265. }
  266. EXPORT_SYMBOL_GPL(iommu_device_unregister);
  267. #if IS_ENABLED(CONFIG_IOMMUFD_TEST)
  268. void iommu_device_unregister_bus(struct iommu_device *iommu,
  269. const struct bus_type *bus,
  270. struct notifier_block *nb)
  271. {
  272. bus_unregister_notifier(bus, nb);
  273. fwnode_remove_software_node(iommu->fwnode);
  274. iommu_device_unregister(iommu);
  275. }
  276. EXPORT_SYMBOL_GPL(iommu_device_unregister_bus);
  277. /*
  278. * Register an iommu driver against a single bus. This is only used by iommufd
  279. * selftest to create a mock iommu driver. The caller must provide
  280. * some memory to hold a notifier_block.
  281. */
  282. int iommu_device_register_bus(struct iommu_device *iommu,
  283. const struct iommu_ops *ops,
  284. const struct bus_type *bus,
  285. struct notifier_block *nb)
  286. {
  287. int err;
  288. iommu->ops = ops;
  289. nb->notifier_call = iommu_bus_notifier;
  290. err = bus_register_notifier(bus, nb);
  291. if (err)
  292. return err;
  293. iommu->fwnode = fwnode_create_software_node(NULL, NULL);
  294. if (IS_ERR(iommu->fwnode)) {
  295. bus_unregister_notifier(bus, nb);
  296. return PTR_ERR(iommu->fwnode);
  297. }
  298. spin_lock(&iommu_device_lock);
  299. list_add_tail(&iommu->list, &iommu_device_list);
  300. spin_unlock(&iommu_device_lock);
  301. err = bus_iommu_probe(bus);
  302. if (err) {
  303. iommu_device_unregister_bus(iommu, bus, nb);
  304. return err;
  305. }
  306. WRITE_ONCE(iommu->ready, true);
  307. return 0;
  308. }
  309. EXPORT_SYMBOL_GPL(iommu_device_register_bus);
  310. int iommu_mock_device_add(struct device *dev, struct iommu_device *iommu)
  311. {
  312. int rc;
  313. mutex_lock(&iommu_probe_device_lock);
  314. rc = iommu_fwspec_init(dev, iommu->fwnode);
  315. mutex_unlock(&iommu_probe_device_lock);
  316. if (rc)
  317. return rc;
  318. rc = device_add(dev);
  319. if (rc)
  320. iommu_fwspec_free(dev);
  321. return rc;
  322. }
  323. EXPORT_SYMBOL_GPL(iommu_mock_device_add);
  324. #endif
  325. static struct dev_iommu *dev_iommu_get(struct device *dev)
  326. {
  327. struct dev_iommu *param = dev->iommu;
  328. lockdep_assert_held(&iommu_probe_device_lock);
  329. if (param)
  330. return param;
  331. param = kzalloc_obj(*param);
  332. if (!param)
  333. return NULL;
  334. mutex_init(&param->lock);
  335. dev->iommu = param;
  336. return param;
  337. }
  338. void dev_iommu_free(struct device *dev)
  339. {
  340. struct dev_iommu *param = dev->iommu;
  341. dev->iommu = NULL;
  342. if (param->fwspec) {
  343. fwnode_handle_put(param->fwspec->iommu_fwnode);
  344. kfree(param->fwspec);
  345. }
  346. kfree(param);
  347. }
  348. /*
  349. * Internal equivalent of device_iommu_mapped() for when we care that a device
  350. * actually has API ops, and don't want false positives from VFIO-only groups.
  351. */
  352. static bool dev_has_iommu(struct device *dev)
  353. {
  354. return dev->iommu && dev->iommu->iommu_dev;
  355. }
  356. static u32 dev_iommu_get_max_pasids(struct device *dev)
  357. {
  358. u32 max_pasids = 0, bits = 0;
  359. int ret;
  360. if (dev_is_pci(dev)) {
  361. ret = pci_max_pasids(to_pci_dev(dev));
  362. if (ret > 0)
  363. max_pasids = ret;
  364. } else {
  365. ret = device_property_read_u32(dev, "pasid-num-bits", &bits);
  366. if (!ret)
  367. max_pasids = 1UL << bits;
  368. }
  369. return min_t(u32, max_pasids, dev->iommu->iommu_dev->max_pasids);
  370. }
  371. void dev_iommu_priv_set(struct device *dev, void *priv)
  372. {
  373. /* FSL_PAMU does something weird */
  374. if (!IS_ENABLED(CONFIG_FSL_PAMU))
  375. lockdep_assert_held(&iommu_probe_device_lock);
  376. dev->iommu->priv = priv;
  377. }
  378. EXPORT_SYMBOL_GPL(dev_iommu_priv_set);
  379. /*
  380. * Init the dev->iommu and dev->iommu_group in the struct device and get the
  381. * driver probed
  382. */
  383. static int iommu_init_device(struct device *dev)
  384. {
  385. const struct iommu_ops *ops;
  386. struct iommu_device *iommu_dev;
  387. struct iommu_group *group;
  388. int ret;
  389. if (!dev_iommu_get(dev))
  390. return -ENOMEM;
  391. /*
  392. * For FDT-based systems and ACPI IORT/VIOT, the common firmware parsing
  393. * is buried in the bus dma_configure path. Properly unpicking that is
  394. * still a big job, so for now just invoke the whole thing. The device
  395. * already having a driver bound means dma_configure has already run and
  396. * found no IOMMU to wait for, so there's no point calling it again.
  397. */
  398. if (!dev->iommu->fwspec && !dev->driver && dev->bus->dma_configure) {
  399. mutex_unlock(&iommu_probe_device_lock);
  400. dev->bus->dma_configure(dev);
  401. mutex_lock(&iommu_probe_device_lock);
  402. /* If another instance finished the job for us, skip it */
  403. if (!dev->iommu || dev->iommu_group)
  404. return -ENODEV;
  405. }
  406. /*
  407. * At this point, relevant devices either now have a fwspec which will
  408. * match ops registered with a non-NULL fwnode, or we can reasonably
  409. * assume that only one of Intel, AMD, s390, PAMU or legacy SMMUv2 can
  410. * be present, and that any of their registered instances has suitable
  411. * ops for probing, and thus cheekily co-opt the same mechanism.
  412. */
  413. ops = iommu_fwspec_ops(dev->iommu->fwspec);
  414. if (!ops) {
  415. ret = -ENODEV;
  416. goto err_free;
  417. }
  418. if (!try_module_get(ops->owner)) {
  419. ret = -EINVAL;
  420. goto err_free;
  421. }
  422. iommu_dev = ops->probe_device(dev);
  423. if (IS_ERR(iommu_dev)) {
  424. ret = PTR_ERR(iommu_dev);
  425. goto err_module_put;
  426. }
  427. dev->iommu->iommu_dev = iommu_dev;
  428. ret = iommu_device_link(iommu_dev, dev);
  429. if (ret)
  430. goto err_release;
  431. group = ops->device_group(dev);
  432. if (WARN_ON_ONCE(group == NULL))
  433. group = ERR_PTR(-EINVAL);
  434. if (IS_ERR(group)) {
  435. ret = PTR_ERR(group);
  436. goto err_unlink;
  437. }
  438. dev->iommu_group = group;
  439. dev->iommu->max_pasids = dev_iommu_get_max_pasids(dev);
  440. if (ops->is_attach_deferred)
  441. dev->iommu->attach_deferred = ops->is_attach_deferred(dev);
  442. return 0;
  443. err_unlink:
  444. iommu_device_unlink(iommu_dev, dev);
  445. err_release:
  446. if (ops->release_device)
  447. ops->release_device(dev);
  448. err_module_put:
  449. module_put(ops->owner);
  450. err_free:
  451. dev->iommu->iommu_dev = NULL;
  452. dev_iommu_free(dev);
  453. return ret;
  454. }
  455. static void iommu_deinit_device(struct device *dev)
  456. {
  457. struct iommu_group *group = dev->iommu_group;
  458. const struct iommu_ops *ops = dev_iommu_ops(dev);
  459. lockdep_assert_held(&group->mutex);
  460. iommu_device_unlink(dev->iommu->iommu_dev, dev);
  461. /*
  462. * release_device() must stop using any attached domain on the device.
  463. * If there are still other devices in the group, they are not affected
  464. * by this callback.
  465. *
  466. * If the iommu driver provides release_domain, the core code ensures
  467. * that domain is attached prior to calling release_device. Drivers can
  468. * use this to enforce a translation on the idle iommu. Typically, the
  469. * global static blocked_domain is a good choice.
  470. *
  471. * Otherwise, the iommu driver must set the device to either an identity
  472. * or a blocking translation in release_device() and stop using any
  473. * domain pointer, as it is going to be freed.
  474. *
  475. * Regardless, if a delayed attach never occurred, then the release
  476. * should still avoid touching any hardware configuration either.
  477. */
  478. if (!dev->iommu->attach_deferred && ops->release_domain) {
  479. struct iommu_domain *release_domain = ops->release_domain;
  480. /*
  481. * If the device requires direct mappings then it should not
  482. * be parked on a BLOCKED domain during release as that would
  483. * break the direct mappings.
  484. */
  485. if (dev->iommu->require_direct && ops->identity_domain &&
  486. release_domain == ops->blocked_domain)
  487. release_domain = ops->identity_domain;
  488. release_domain->ops->attach_dev(release_domain, dev,
  489. group->domain);
  490. }
  491. if (ops->release_device)
  492. ops->release_device(dev);
  493. /*
  494. * If this is the last driver to use the group then we must free the
  495. * domains before we do the module_put().
  496. */
  497. if (list_empty(&group->devices)) {
  498. if (group->default_domain) {
  499. iommu_domain_free(group->default_domain);
  500. group->default_domain = NULL;
  501. }
  502. if (group->blocking_domain) {
  503. iommu_domain_free(group->blocking_domain);
  504. group->blocking_domain = NULL;
  505. }
  506. group->domain = NULL;
  507. }
  508. /* Caller must put iommu_group */
  509. dev->iommu_group = NULL;
  510. module_put(ops->owner);
  511. dev_iommu_free(dev);
  512. #ifdef CONFIG_IOMMU_DMA
  513. dev->dma_iommu = false;
  514. #endif
  515. }
  516. static struct iommu_domain *pasid_array_entry_to_domain(void *entry)
  517. {
  518. if (xa_pointer_tag(entry) == IOMMU_PASID_ARRAY_DOMAIN)
  519. return xa_untag_pointer(entry);
  520. return ((struct iommu_attach_handle *)xa_untag_pointer(entry))->domain;
  521. }
  522. DEFINE_MUTEX(iommu_probe_device_lock);
  523. static int __iommu_probe_device(struct device *dev, struct list_head *group_list)
  524. {
  525. struct iommu_group *group;
  526. struct group_device *gdev;
  527. int ret;
  528. /*
  529. * Serialise to avoid races between IOMMU drivers registering in
  530. * parallel and/or the "replay" calls from ACPI/OF code via client
  531. * driver probe. Once the latter have been cleaned up we should
  532. * probably be able to use device_lock() here to minimise the scope,
  533. * but for now enforcing a simple global ordering is fine.
  534. */
  535. lockdep_assert_held(&iommu_probe_device_lock);
  536. /* Device is probed already if in a group */
  537. if (dev->iommu_group)
  538. return 0;
  539. ret = iommu_init_device(dev);
  540. if (ret)
  541. return ret;
  542. /*
  543. * And if we do now see any replay calls, they would indicate someone
  544. * misusing the dma_configure path outside bus code.
  545. */
  546. if (dev->driver)
  547. dev_WARN(dev, "late IOMMU probe at driver bind, something fishy here!\n");
  548. group = dev->iommu_group;
  549. gdev = iommu_group_alloc_device(group, dev);
  550. mutex_lock(&group->mutex);
  551. if (IS_ERR(gdev)) {
  552. ret = PTR_ERR(gdev);
  553. goto err_put_group;
  554. }
  555. /*
  556. * The gdev must be in the list before calling
  557. * iommu_setup_default_domain()
  558. */
  559. list_add_tail(&gdev->list, &group->devices);
  560. WARN_ON(group->default_domain && !group->domain);
  561. if (group->default_domain)
  562. iommu_create_device_direct_mappings(group->default_domain, dev);
  563. if (group->domain) {
  564. ret = __iommu_device_set_domain(group, dev, group->domain, NULL,
  565. 0);
  566. if (ret)
  567. goto err_remove_gdev;
  568. } else if (!group->default_domain && !group_list) {
  569. ret = iommu_setup_default_domain(group, 0);
  570. if (ret)
  571. goto err_remove_gdev;
  572. } else if (!group->default_domain) {
  573. /*
  574. * With a group_list argument we defer the default_domain setup
  575. * to the caller by providing a de-duplicated list of groups
  576. * that need further setup.
  577. */
  578. if (list_empty(&group->entry))
  579. list_add_tail(&group->entry, group_list);
  580. }
  581. if (group->default_domain)
  582. iommu_setup_dma_ops(dev, group->default_domain);
  583. mutex_unlock(&group->mutex);
  584. return 0;
  585. err_remove_gdev:
  586. list_del(&gdev->list);
  587. __iommu_group_free_device(group, gdev);
  588. err_put_group:
  589. iommu_deinit_device(dev);
  590. mutex_unlock(&group->mutex);
  591. iommu_group_put(group);
  592. return ret;
  593. }
  594. int iommu_probe_device(struct device *dev)
  595. {
  596. const struct iommu_ops *ops;
  597. int ret;
  598. mutex_lock(&iommu_probe_device_lock);
  599. ret = __iommu_probe_device(dev, NULL);
  600. mutex_unlock(&iommu_probe_device_lock);
  601. if (ret)
  602. return ret;
  603. ops = dev_iommu_ops(dev);
  604. if (ops->probe_finalize)
  605. ops->probe_finalize(dev);
  606. return 0;
  607. }
  608. static void __iommu_group_free_device(struct iommu_group *group,
  609. struct group_device *grp_dev)
  610. {
  611. struct device *dev = grp_dev->dev;
  612. sysfs_remove_link(group->devices_kobj, grp_dev->name);
  613. sysfs_remove_link(&dev->kobj, "iommu_group");
  614. trace_remove_device_from_group(group->id, dev);
  615. /*
  616. * If the group has become empty then ownership must have been
  617. * released, and the current domain must be set back to NULL or
  618. * the default domain.
  619. */
  620. if (list_empty(&group->devices))
  621. WARN_ON(group->owner_cnt ||
  622. group->domain != group->default_domain);
  623. kfree(grp_dev->name);
  624. kfree(grp_dev);
  625. }
  626. /* Remove the iommu_group from the struct device. */
  627. static void __iommu_group_remove_device(struct device *dev)
  628. {
  629. struct iommu_group *group = dev->iommu_group;
  630. struct group_device *device;
  631. mutex_lock(&group->mutex);
  632. for_each_group_device(group, device) {
  633. if (device->dev != dev)
  634. continue;
  635. list_del(&device->list);
  636. __iommu_group_free_device(group, device);
  637. if (dev_has_iommu(dev))
  638. iommu_deinit_device(dev);
  639. else
  640. dev->iommu_group = NULL;
  641. break;
  642. }
  643. mutex_unlock(&group->mutex);
  644. /*
  645. * Pairs with the get in iommu_init_device() or
  646. * iommu_group_add_device()
  647. */
  648. iommu_group_put(group);
  649. }
  650. static void iommu_release_device(struct device *dev)
  651. {
  652. struct iommu_group *group = dev->iommu_group;
  653. if (group)
  654. __iommu_group_remove_device(dev);
  655. /* Free any fwspec if no iommu_driver was ever attached */
  656. if (dev->iommu)
  657. dev_iommu_free(dev);
  658. }
  659. static int __init iommu_set_def_domain_type(char *str)
  660. {
  661. bool pt;
  662. int ret;
  663. ret = kstrtobool(str, &pt);
  664. if (ret)
  665. return ret;
  666. if (pt)
  667. iommu_set_default_passthrough(true);
  668. else
  669. iommu_set_default_translated(true);
  670. return 0;
  671. }
  672. early_param("iommu.passthrough", iommu_set_def_domain_type);
  673. static int __init iommu_dma_setup(char *str)
  674. {
  675. int ret = kstrtobool(str, &iommu_dma_strict);
  676. if (!ret)
  677. iommu_cmd_line |= IOMMU_CMD_LINE_STRICT;
  678. return ret;
  679. }
  680. early_param("iommu.strict", iommu_dma_setup);
  681. void iommu_set_dma_strict(void)
  682. {
  683. iommu_dma_strict = true;
  684. if (iommu_def_domain_type == IOMMU_DOMAIN_DMA_FQ)
  685. iommu_def_domain_type = IOMMU_DOMAIN_DMA;
  686. }
  687. static ssize_t iommu_group_attr_show(struct kobject *kobj,
  688. struct attribute *__attr, char *buf)
  689. {
  690. struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
  691. struct iommu_group *group = to_iommu_group(kobj);
  692. ssize_t ret = -EIO;
  693. if (attr->show)
  694. ret = attr->show(group, buf);
  695. return ret;
  696. }
  697. static ssize_t iommu_group_attr_store(struct kobject *kobj,
  698. struct attribute *__attr,
  699. const char *buf, size_t count)
  700. {
  701. struct iommu_group_attribute *attr = to_iommu_group_attr(__attr);
  702. struct iommu_group *group = to_iommu_group(kobj);
  703. ssize_t ret = -EIO;
  704. if (attr->store)
  705. ret = attr->store(group, buf, count);
  706. return ret;
  707. }
  708. static const struct sysfs_ops iommu_group_sysfs_ops = {
  709. .show = iommu_group_attr_show,
  710. .store = iommu_group_attr_store,
  711. };
  712. static int iommu_group_create_file(struct iommu_group *group,
  713. struct iommu_group_attribute *attr)
  714. {
  715. return sysfs_create_file(&group->kobj, &attr->attr);
  716. }
  717. static void iommu_group_remove_file(struct iommu_group *group,
  718. struct iommu_group_attribute *attr)
  719. {
  720. sysfs_remove_file(&group->kobj, &attr->attr);
  721. }
  722. static ssize_t iommu_group_show_name(struct iommu_group *group, char *buf)
  723. {
  724. return sysfs_emit(buf, "%s\n", group->name);
  725. }
  726. /**
  727. * iommu_insert_resv_region - Insert a new region in the
  728. * list of reserved regions.
  729. * @new: new region to insert
  730. * @regions: list of regions
  731. *
  732. * Elements are sorted by start address and overlapping segments
  733. * of the same type are merged.
  734. */
  735. static int iommu_insert_resv_region(struct iommu_resv_region *new,
  736. struct list_head *regions)
  737. {
  738. struct iommu_resv_region *iter, *tmp, *nr, *top;
  739. LIST_HEAD(stack);
  740. nr = iommu_alloc_resv_region(new->start, new->length,
  741. new->prot, new->type, GFP_KERNEL);
  742. if (!nr)
  743. return -ENOMEM;
  744. /* First add the new element based on start address sorting */
  745. list_for_each_entry(iter, regions, list) {
  746. if (nr->start < iter->start ||
  747. (nr->start == iter->start && nr->type <= iter->type))
  748. break;
  749. }
  750. list_add_tail(&nr->list, &iter->list);
  751. /* Merge overlapping segments of type nr->type in @regions, if any */
  752. list_for_each_entry_safe(iter, tmp, regions, list) {
  753. phys_addr_t top_end, iter_end = iter->start + iter->length - 1;
  754. /* no merge needed on elements of different types than @new */
  755. if (iter->type != new->type) {
  756. list_move_tail(&iter->list, &stack);
  757. continue;
  758. }
  759. /* look for the last stack element of same type as @iter */
  760. list_for_each_entry_reverse(top, &stack, list)
  761. if (top->type == iter->type)
  762. goto check_overlap;
  763. list_move_tail(&iter->list, &stack);
  764. continue;
  765. check_overlap:
  766. top_end = top->start + top->length - 1;
  767. if (iter->start > top_end + 1) {
  768. list_move_tail(&iter->list, &stack);
  769. } else {
  770. top->length = max(top_end, iter_end) - top->start + 1;
  771. list_del(&iter->list);
  772. kfree(iter);
  773. }
  774. }
  775. list_splice(&stack, regions);
  776. return 0;
  777. }
  778. static int
  779. iommu_insert_device_resv_regions(struct list_head *dev_resv_regions,
  780. struct list_head *group_resv_regions)
  781. {
  782. struct iommu_resv_region *entry;
  783. int ret = 0;
  784. list_for_each_entry(entry, dev_resv_regions, list) {
  785. ret = iommu_insert_resv_region(entry, group_resv_regions);
  786. if (ret)
  787. break;
  788. }
  789. return ret;
  790. }
  791. int iommu_get_group_resv_regions(struct iommu_group *group,
  792. struct list_head *head)
  793. {
  794. struct group_device *device;
  795. int ret = 0;
  796. mutex_lock(&group->mutex);
  797. for_each_group_device(group, device) {
  798. struct list_head dev_resv_regions;
  799. /*
  800. * Non-API groups still expose reserved_regions in sysfs,
  801. * so filter out calls that get here that way.
  802. */
  803. if (!dev_has_iommu(device->dev))
  804. break;
  805. INIT_LIST_HEAD(&dev_resv_regions);
  806. iommu_get_resv_regions(device->dev, &dev_resv_regions);
  807. ret = iommu_insert_device_resv_regions(&dev_resv_regions, head);
  808. iommu_put_resv_regions(device->dev, &dev_resv_regions);
  809. if (ret)
  810. break;
  811. }
  812. mutex_unlock(&group->mutex);
  813. return ret;
  814. }
  815. EXPORT_SYMBOL_GPL(iommu_get_group_resv_regions);
  816. static ssize_t iommu_group_show_resv_regions(struct iommu_group *group,
  817. char *buf)
  818. {
  819. struct iommu_resv_region *region, *next;
  820. struct list_head group_resv_regions;
  821. int offset = 0;
  822. INIT_LIST_HEAD(&group_resv_regions);
  823. iommu_get_group_resv_regions(group, &group_resv_regions);
  824. list_for_each_entry_safe(region, next, &group_resv_regions, list) {
  825. offset += sysfs_emit_at(buf, offset, "0x%016llx 0x%016llx %s\n",
  826. (long long)region->start,
  827. (long long)(region->start +
  828. region->length - 1),
  829. iommu_group_resv_type_string[region->type]);
  830. kfree(region);
  831. }
  832. return offset;
  833. }
  834. static ssize_t iommu_group_show_type(struct iommu_group *group,
  835. char *buf)
  836. {
  837. char *type = "unknown";
  838. mutex_lock(&group->mutex);
  839. if (group->default_domain) {
  840. switch (group->default_domain->type) {
  841. case IOMMU_DOMAIN_BLOCKED:
  842. type = "blocked";
  843. break;
  844. case IOMMU_DOMAIN_IDENTITY:
  845. type = "identity";
  846. break;
  847. case IOMMU_DOMAIN_UNMANAGED:
  848. type = "unmanaged";
  849. break;
  850. case IOMMU_DOMAIN_DMA:
  851. type = "DMA";
  852. break;
  853. case IOMMU_DOMAIN_DMA_FQ:
  854. type = "DMA-FQ";
  855. break;
  856. }
  857. }
  858. mutex_unlock(&group->mutex);
  859. return sysfs_emit(buf, "%s\n", type);
  860. }
  861. static IOMMU_GROUP_ATTR(name, S_IRUGO, iommu_group_show_name, NULL);
  862. static IOMMU_GROUP_ATTR(reserved_regions, 0444,
  863. iommu_group_show_resv_regions, NULL);
  864. static IOMMU_GROUP_ATTR(type, 0644, iommu_group_show_type,
  865. iommu_group_store_type);
  866. static void iommu_group_release(struct kobject *kobj)
  867. {
  868. struct iommu_group *group = to_iommu_group(kobj);
  869. pr_debug("Releasing group %d\n", group->id);
  870. if (group->iommu_data_release)
  871. group->iommu_data_release(group->iommu_data);
  872. ida_free(&iommu_group_ida, group->id);
  873. /* Domains are free'd by iommu_deinit_device() */
  874. WARN_ON(group->default_domain);
  875. WARN_ON(group->blocking_domain);
  876. kfree(group->name);
  877. kfree(group);
  878. }
  879. static const struct kobj_type iommu_group_ktype = {
  880. .sysfs_ops = &iommu_group_sysfs_ops,
  881. .release = iommu_group_release,
  882. };
  883. /**
  884. * iommu_group_alloc - Allocate a new group
  885. *
  886. * This function is called by an iommu driver to allocate a new iommu
  887. * group. The iommu group represents the minimum granularity of the iommu.
  888. * Upon successful return, the caller holds a reference to the supplied
  889. * group in order to hold the group until devices are added. Use
  890. * iommu_group_put() to release this extra reference count, allowing the
  891. * group to be automatically reclaimed once it has no devices or external
  892. * references.
  893. */
  894. struct iommu_group *iommu_group_alloc(void)
  895. {
  896. struct iommu_group *group;
  897. int ret;
  898. group = kzalloc_obj(*group);
  899. if (!group)
  900. return ERR_PTR(-ENOMEM);
  901. group->kobj.kset = iommu_group_kset;
  902. mutex_init(&group->mutex);
  903. INIT_LIST_HEAD(&group->devices);
  904. INIT_LIST_HEAD(&group->entry);
  905. xa_init(&group->pasid_array);
  906. ret = ida_alloc(&iommu_group_ida, GFP_KERNEL);
  907. if (ret < 0) {
  908. kfree(group);
  909. return ERR_PTR(ret);
  910. }
  911. group->id = ret;
  912. ret = kobject_init_and_add(&group->kobj, &iommu_group_ktype,
  913. NULL, "%d", group->id);
  914. if (ret) {
  915. kobject_put(&group->kobj);
  916. return ERR_PTR(ret);
  917. }
  918. group->devices_kobj = kobject_create_and_add("devices", &group->kobj);
  919. if (!group->devices_kobj) {
  920. kobject_put(&group->kobj); /* triggers .release & free */
  921. return ERR_PTR(-ENOMEM);
  922. }
  923. /*
  924. * The devices_kobj holds a reference on the group kobject, so
  925. * as long as that exists so will the group. We can therefore
  926. * use the devices_kobj for reference counting.
  927. */
  928. kobject_put(&group->kobj);
  929. ret = iommu_group_create_file(group,
  930. &iommu_group_attr_reserved_regions);
  931. if (ret) {
  932. kobject_put(group->devices_kobj);
  933. return ERR_PTR(ret);
  934. }
  935. ret = iommu_group_create_file(group, &iommu_group_attr_type);
  936. if (ret) {
  937. kobject_put(group->devices_kobj);
  938. return ERR_PTR(ret);
  939. }
  940. pr_debug("Allocated group %d\n", group->id);
  941. return group;
  942. }
  943. EXPORT_SYMBOL_GPL(iommu_group_alloc);
  944. /**
  945. * iommu_group_get_iommudata - retrieve iommu_data registered for a group
  946. * @group: the group
  947. *
  948. * iommu drivers can store data in the group for use when doing iommu
  949. * operations. This function provides a way to retrieve it. Caller
  950. * should hold a group reference.
  951. */
  952. void *iommu_group_get_iommudata(struct iommu_group *group)
  953. {
  954. return group->iommu_data;
  955. }
  956. EXPORT_SYMBOL_GPL(iommu_group_get_iommudata);
  957. /**
  958. * iommu_group_set_iommudata - set iommu_data for a group
  959. * @group: the group
  960. * @iommu_data: new data
  961. * @release: release function for iommu_data
  962. *
  963. * iommu drivers can store data in the group for use when doing iommu
  964. * operations. This function provides a way to set the data after
  965. * the group has been allocated. Caller should hold a group reference.
  966. */
  967. void iommu_group_set_iommudata(struct iommu_group *group, void *iommu_data,
  968. void (*release)(void *iommu_data))
  969. {
  970. group->iommu_data = iommu_data;
  971. group->iommu_data_release = release;
  972. }
  973. EXPORT_SYMBOL_GPL(iommu_group_set_iommudata);
  974. /**
  975. * iommu_group_set_name - set name for a group
  976. * @group: the group
  977. * @name: name
  978. *
  979. * Allow iommu driver to set a name for a group. When set it will
  980. * appear in a name attribute file under the group in sysfs.
  981. */
  982. int iommu_group_set_name(struct iommu_group *group, const char *name)
  983. {
  984. int ret;
  985. if (group->name) {
  986. iommu_group_remove_file(group, &iommu_group_attr_name);
  987. kfree(group->name);
  988. group->name = NULL;
  989. if (!name)
  990. return 0;
  991. }
  992. group->name = kstrdup(name, GFP_KERNEL);
  993. if (!group->name)
  994. return -ENOMEM;
  995. ret = iommu_group_create_file(group, &iommu_group_attr_name);
  996. if (ret) {
  997. kfree(group->name);
  998. group->name = NULL;
  999. return ret;
  1000. }
  1001. return 0;
  1002. }
  1003. EXPORT_SYMBOL_GPL(iommu_group_set_name);
  1004. static int iommu_create_device_direct_mappings(struct iommu_domain *domain,
  1005. struct device *dev)
  1006. {
  1007. struct iommu_resv_region *entry;
  1008. LIST_HEAD(mappings);
  1009. unsigned long pg_size;
  1010. int ret = 0;
  1011. pg_size = domain->pgsize_bitmap ? 1UL << __ffs(domain->pgsize_bitmap) : 0;
  1012. if (WARN_ON_ONCE(iommu_is_dma_domain(domain) && !pg_size))
  1013. return -EINVAL;
  1014. iommu_get_resv_regions(dev, &mappings);
  1015. /* We need to consider overlapping regions for different devices */
  1016. list_for_each_entry(entry, &mappings, list) {
  1017. dma_addr_t start, end, addr;
  1018. size_t map_size = 0;
  1019. if (entry->type == IOMMU_RESV_DIRECT)
  1020. dev->iommu->require_direct = 1;
  1021. if ((entry->type != IOMMU_RESV_DIRECT &&
  1022. entry->type != IOMMU_RESV_DIRECT_RELAXABLE) ||
  1023. !iommu_is_dma_domain(domain))
  1024. continue;
  1025. start = ALIGN(entry->start, pg_size);
  1026. end = ALIGN(entry->start + entry->length, pg_size);
  1027. for (addr = start; addr <= end; addr += pg_size) {
  1028. phys_addr_t phys_addr;
  1029. if (addr == end)
  1030. goto map_end;
  1031. /*
  1032. * Return address by iommu_iova_to_phys for 0 is
  1033. * ambiguous. Offset to address 1 if addr is 0.
  1034. */
  1035. phys_addr = iommu_iova_to_phys(domain, addr ? addr : 1);
  1036. if (!phys_addr) {
  1037. map_size += pg_size;
  1038. continue;
  1039. }
  1040. map_end:
  1041. if (map_size) {
  1042. ret = iommu_map(domain, addr - map_size,
  1043. addr - map_size, map_size,
  1044. entry->prot, GFP_KERNEL);
  1045. if (ret)
  1046. goto out;
  1047. map_size = 0;
  1048. }
  1049. }
  1050. }
  1051. out:
  1052. iommu_put_resv_regions(dev, &mappings);
  1053. return ret;
  1054. }
  1055. /* This is undone by __iommu_group_free_device() */
  1056. static struct group_device *iommu_group_alloc_device(struct iommu_group *group,
  1057. struct device *dev)
  1058. {
  1059. int ret, i = 0;
  1060. struct group_device *device;
  1061. device = kzalloc_obj(*device);
  1062. if (!device)
  1063. return ERR_PTR(-ENOMEM);
  1064. device->dev = dev;
  1065. ret = sysfs_create_link(&dev->kobj, &group->kobj, "iommu_group");
  1066. if (ret)
  1067. goto err_free_device;
  1068. device->name = kasprintf(GFP_KERNEL, "%s", kobject_name(&dev->kobj));
  1069. rename:
  1070. if (!device->name) {
  1071. ret = -ENOMEM;
  1072. goto err_remove_link;
  1073. }
  1074. ret = sysfs_create_link_nowarn(group->devices_kobj,
  1075. &dev->kobj, device->name);
  1076. if (ret) {
  1077. if (ret == -EEXIST && i >= 0) {
  1078. /*
  1079. * Account for the slim chance of collision
  1080. * and append an instance to the name.
  1081. */
  1082. kfree(device->name);
  1083. device->name = kasprintf(GFP_KERNEL, "%s.%d",
  1084. kobject_name(&dev->kobj), i++);
  1085. goto rename;
  1086. }
  1087. goto err_free_name;
  1088. }
  1089. trace_add_device_to_group(group->id, dev);
  1090. dev_info(dev, "Adding to iommu group %d\n", group->id);
  1091. return device;
  1092. err_free_name:
  1093. kfree(device->name);
  1094. err_remove_link:
  1095. sysfs_remove_link(&dev->kobj, "iommu_group");
  1096. err_free_device:
  1097. kfree(device);
  1098. dev_err(dev, "Failed to add to iommu group %d: %d\n", group->id, ret);
  1099. return ERR_PTR(ret);
  1100. }
  1101. /**
  1102. * iommu_group_add_device - add a device to an iommu group
  1103. * @group: the group into which to add the device (reference should be held)
  1104. * @dev: the device
  1105. *
  1106. * This function is called by an iommu driver to add a device into a
  1107. * group. Adding a device increments the group reference count.
  1108. */
  1109. int iommu_group_add_device(struct iommu_group *group, struct device *dev)
  1110. {
  1111. struct group_device *gdev;
  1112. gdev = iommu_group_alloc_device(group, dev);
  1113. if (IS_ERR(gdev))
  1114. return PTR_ERR(gdev);
  1115. iommu_group_ref_get(group);
  1116. dev->iommu_group = group;
  1117. mutex_lock(&group->mutex);
  1118. list_add_tail(&gdev->list, &group->devices);
  1119. mutex_unlock(&group->mutex);
  1120. return 0;
  1121. }
  1122. EXPORT_SYMBOL_GPL(iommu_group_add_device);
  1123. /**
  1124. * iommu_group_remove_device - remove a device from it's current group
  1125. * @dev: device to be removed
  1126. *
  1127. * This function is called by an iommu driver to remove the device from
  1128. * it's current group. This decrements the iommu group reference count.
  1129. */
  1130. void iommu_group_remove_device(struct device *dev)
  1131. {
  1132. struct iommu_group *group = dev->iommu_group;
  1133. if (!group)
  1134. return;
  1135. dev_info(dev, "Removing from iommu group %d\n", group->id);
  1136. __iommu_group_remove_device(dev);
  1137. }
  1138. EXPORT_SYMBOL_GPL(iommu_group_remove_device);
  1139. #if IS_ENABLED(CONFIG_LOCKDEP) && IS_ENABLED(CONFIG_IOMMU_API)
  1140. /**
  1141. * iommu_group_mutex_assert - Check device group mutex lock
  1142. * @dev: the device that has group param set
  1143. *
  1144. * This function is called by an iommu driver to check whether it holds
  1145. * group mutex lock for the given device or not.
  1146. *
  1147. * Note that this function must be called after device group param is set.
  1148. */
  1149. void iommu_group_mutex_assert(struct device *dev)
  1150. {
  1151. struct iommu_group *group = dev->iommu_group;
  1152. lockdep_assert_held(&group->mutex);
  1153. }
  1154. EXPORT_SYMBOL_GPL(iommu_group_mutex_assert);
  1155. #endif
  1156. static struct device *iommu_group_first_dev(struct iommu_group *group)
  1157. {
  1158. lockdep_assert_held(&group->mutex);
  1159. return list_first_entry(&group->devices, struct group_device, list)->dev;
  1160. }
  1161. /**
  1162. * iommu_group_for_each_dev - iterate over each device in the group
  1163. * @group: the group
  1164. * @data: caller opaque data to be passed to callback function
  1165. * @fn: caller supplied callback function
  1166. *
  1167. * This function is called by group users to iterate over group devices.
  1168. * Callers should hold a reference count to the group during callback.
  1169. * The group->mutex is held across callbacks, which will block calls to
  1170. * iommu_group_add/remove_device.
  1171. */
  1172. int iommu_group_for_each_dev(struct iommu_group *group, void *data,
  1173. int (*fn)(struct device *, void *))
  1174. {
  1175. struct group_device *device;
  1176. int ret = 0;
  1177. mutex_lock(&group->mutex);
  1178. for_each_group_device(group, device) {
  1179. ret = fn(device->dev, data);
  1180. if (ret)
  1181. break;
  1182. }
  1183. mutex_unlock(&group->mutex);
  1184. return ret;
  1185. }
  1186. EXPORT_SYMBOL_GPL(iommu_group_for_each_dev);
  1187. /**
  1188. * iommu_group_get - Return the group for a device and increment reference
  1189. * @dev: get the group that this device belongs to
  1190. *
  1191. * This function is called by iommu drivers and users to get the group
  1192. * for the specified device. If found, the group is returned and the group
  1193. * reference in incremented, else NULL.
  1194. */
  1195. struct iommu_group *iommu_group_get(struct device *dev)
  1196. {
  1197. struct iommu_group *group = dev->iommu_group;
  1198. if (group)
  1199. kobject_get(group->devices_kobj);
  1200. return group;
  1201. }
  1202. EXPORT_SYMBOL_GPL(iommu_group_get);
  1203. /**
  1204. * iommu_group_ref_get - Increment reference on a group
  1205. * @group: the group to use, must not be NULL
  1206. *
  1207. * This function is called by iommu drivers to take additional references on an
  1208. * existing group. Returns the given group for convenience.
  1209. */
  1210. struct iommu_group *iommu_group_ref_get(struct iommu_group *group)
  1211. {
  1212. kobject_get(group->devices_kobj);
  1213. return group;
  1214. }
  1215. EXPORT_SYMBOL_GPL(iommu_group_ref_get);
  1216. /**
  1217. * iommu_group_put - Decrement group reference
  1218. * @group: the group to use
  1219. *
  1220. * This function is called by iommu drivers and users to release the
  1221. * iommu group. Once the reference count is zero, the group is released.
  1222. */
  1223. void iommu_group_put(struct iommu_group *group)
  1224. {
  1225. if (group)
  1226. kobject_put(group->devices_kobj);
  1227. }
  1228. EXPORT_SYMBOL_GPL(iommu_group_put);
  1229. /**
  1230. * iommu_group_id - Return ID for a group
  1231. * @group: the group to ID
  1232. *
  1233. * Return the unique ID for the group matching the sysfs group number.
  1234. */
  1235. int iommu_group_id(struct iommu_group *group)
  1236. {
  1237. return group->id;
  1238. }
  1239. EXPORT_SYMBOL_GPL(iommu_group_id);
  1240. static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
  1241. unsigned long *devfns);
  1242. /*
  1243. * To consider a PCI device isolated, we require ACS to support Source
  1244. * Validation, Request Redirection, Completer Redirection, and Upstream
  1245. * Forwarding. This effectively means that devices cannot spoof their
  1246. * requester ID, requests and completions cannot be redirected, and all
  1247. * transactions are forwarded upstream, even as it passes through a
  1248. * bridge where the target device is downstream.
  1249. */
  1250. #define REQ_ACS_FLAGS (PCI_ACS_SV | PCI_ACS_RR | PCI_ACS_CR | PCI_ACS_UF)
  1251. /*
  1252. * For multifunction devices which are not isolated from each other, find
  1253. * all the other non-isolated functions and look for existing groups. For
  1254. * each function, we also need to look for aliases to or from other devices
  1255. * that may already have a group.
  1256. */
  1257. static struct iommu_group *get_pci_function_alias_group(struct pci_dev *pdev,
  1258. unsigned long *devfns)
  1259. {
  1260. struct pci_dev *tmp = NULL;
  1261. struct iommu_group *group;
  1262. if (!pdev->multifunction || pci_acs_enabled(pdev, REQ_ACS_FLAGS))
  1263. return NULL;
  1264. for_each_pci_dev(tmp) {
  1265. if (tmp == pdev || tmp->bus != pdev->bus ||
  1266. PCI_SLOT(tmp->devfn) != PCI_SLOT(pdev->devfn) ||
  1267. pci_acs_enabled(tmp, REQ_ACS_FLAGS))
  1268. continue;
  1269. group = get_pci_alias_group(tmp, devfns);
  1270. if (group) {
  1271. pci_dev_put(tmp);
  1272. return group;
  1273. }
  1274. }
  1275. return NULL;
  1276. }
  1277. /*
  1278. * Look for aliases to or from the given device for existing groups. DMA
  1279. * aliases are only supported on the same bus, therefore the search
  1280. * space is quite small (especially since we're really only looking at pcie
  1281. * device, and therefore only expect multiple slots on the root complex or
  1282. * downstream switch ports). It's conceivable though that a pair of
  1283. * multifunction devices could have aliases between them that would cause a
  1284. * loop. To prevent this, we use a bitmap to track where we've been.
  1285. */
  1286. static struct iommu_group *get_pci_alias_group(struct pci_dev *pdev,
  1287. unsigned long *devfns)
  1288. {
  1289. struct pci_dev *tmp = NULL;
  1290. struct iommu_group *group;
  1291. if (test_and_set_bit(pdev->devfn & 0xff, devfns))
  1292. return NULL;
  1293. group = iommu_group_get(&pdev->dev);
  1294. if (group)
  1295. return group;
  1296. for_each_pci_dev(tmp) {
  1297. if (tmp == pdev || tmp->bus != pdev->bus)
  1298. continue;
  1299. /* We alias them or they alias us */
  1300. if (pci_devs_are_dma_aliases(pdev, tmp)) {
  1301. group = get_pci_alias_group(tmp, devfns);
  1302. if (group) {
  1303. pci_dev_put(tmp);
  1304. return group;
  1305. }
  1306. group = get_pci_function_alias_group(tmp, devfns);
  1307. if (group) {
  1308. pci_dev_put(tmp);
  1309. return group;
  1310. }
  1311. }
  1312. }
  1313. return NULL;
  1314. }
  1315. struct group_for_pci_data {
  1316. struct pci_dev *pdev;
  1317. struct iommu_group *group;
  1318. };
  1319. /*
  1320. * DMA alias iterator callback, return the last seen device. Stop and return
  1321. * the IOMMU group if we find one along the way.
  1322. */
  1323. static int get_pci_alias_or_group(struct pci_dev *pdev, u16 alias, void *opaque)
  1324. {
  1325. struct group_for_pci_data *data = opaque;
  1326. data->pdev = pdev;
  1327. data->group = iommu_group_get(&pdev->dev);
  1328. return data->group != NULL;
  1329. }
  1330. /*
  1331. * Generic device_group call-back function. It just allocates one
  1332. * iommu-group per device.
  1333. */
  1334. struct iommu_group *generic_device_group(struct device *dev)
  1335. {
  1336. return iommu_group_alloc();
  1337. }
  1338. EXPORT_SYMBOL_GPL(generic_device_group);
  1339. /*
  1340. * Generic device_group call-back function. It just allocates one
  1341. * iommu-group per iommu driver instance shared by every device
  1342. * probed by that iommu driver.
  1343. */
  1344. struct iommu_group *generic_single_device_group(struct device *dev)
  1345. {
  1346. struct iommu_device *iommu = dev->iommu->iommu_dev;
  1347. if (!iommu->singleton_group) {
  1348. struct iommu_group *group;
  1349. group = iommu_group_alloc();
  1350. if (IS_ERR(group))
  1351. return group;
  1352. iommu->singleton_group = group;
  1353. }
  1354. return iommu_group_ref_get(iommu->singleton_group);
  1355. }
  1356. EXPORT_SYMBOL_GPL(generic_single_device_group);
  1357. /*
  1358. * Use standard PCI bus topology, isolation features, and DMA alias quirks
  1359. * to find or create an IOMMU group for a device.
  1360. */
  1361. struct iommu_group *pci_device_group(struct device *dev)
  1362. {
  1363. struct pci_dev *pdev = to_pci_dev(dev);
  1364. struct group_for_pci_data data;
  1365. struct pci_bus *bus;
  1366. struct iommu_group *group = NULL;
  1367. u64 devfns[4] = { 0 };
  1368. if (WARN_ON(!dev_is_pci(dev)))
  1369. return ERR_PTR(-EINVAL);
  1370. /*
  1371. * Find the upstream DMA alias for the device. A device must not
  1372. * be aliased due to topology in order to have its own IOMMU group.
  1373. * If we find an alias along the way that already belongs to a
  1374. * group, use it.
  1375. */
  1376. if (pci_for_each_dma_alias(pdev, get_pci_alias_or_group, &data))
  1377. return data.group;
  1378. pdev = data.pdev;
  1379. /*
  1380. * Continue upstream from the point of minimum IOMMU granularity
  1381. * due to aliases to the point where devices are protected from
  1382. * peer-to-peer DMA by PCI ACS. Again, if we find an existing
  1383. * group, use it.
  1384. */
  1385. for (bus = pdev->bus; !pci_is_root_bus(bus); bus = bus->parent) {
  1386. if (!bus->self)
  1387. continue;
  1388. if (pci_acs_path_enabled(bus->self, NULL, REQ_ACS_FLAGS))
  1389. break;
  1390. pdev = bus->self;
  1391. group = iommu_group_get(&pdev->dev);
  1392. if (group)
  1393. return group;
  1394. }
  1395. /*
  1396. * Look for existing groups on device aliases. If we alias another
  1397. * device or another device aliases us, use the same group.
  1398. */
  1399. group = get_pci_alias_group(pdev, (unsigned long *)devfns);
  1400. if (group)
  1401. return group;
  1402. /*
  1403. * Look for existing groups on non-isolated functions on the same
  1404. * slot and aliases of those funcions, if any. No need to clear
  1405. * the search bitmap, the tested devfns are still valid.
  1406. */
  1407. group = get_pci_function_alias_group(pdev, (unsigned long *)devfns);
  1408. if (group)
  1409. return group;
  1410. /* No shared group found, allocate new */
  1411. return iommu_group_alloc();
  1412. }
  1413. EXPORT_SYMBOL_GPL(pci_device_group);
  1414. /* Get the IOMMU group for device on fsl-mc bus */
  1415. struct iommu_group *fsl_mc_device_group(struct device *dev)
  1416. {
  1417. struct device *cont_dev = fsl_mc_cont_dev(dev);
  1418. struct iommu_group *group;
  1419. group = iommu_group_get(cont_dev);
  1420. if (!group)
  1421. group = iommu_group_alloc();
  1422. return group;
  1423. }
  1424. EXPORT_SYMBOL_GPL(fsl_mc_device_group);
  1425. static struct iommu_domain *__iommu_alloc_identity_domain(struct device *dev)
  1426. {
  1427. const struct iommu_ops *ops = dev_iommu_ops(dev);
  1428. struct iommu_domain *domain;
  1429. if (ops->identity_domain)
  1430. return ops->identity_domain;
  1431. if (ops->domain_alloc_identity) {
  1432. domain = ops->domain_alloc_identity(dev);
  1433. if (IS_ERR(domain))
  1434. return domain;
  1435. } else {
  1436. return ERR_PTR(-EOPNOTSUPP);
  1437. }
  1438. iommu_domain_init(domain, IOMMU_DOMAIN_IDENTITY, ops);
  1439. return domain;
  1440. }
  1441. static struct iommu_domain *
  1442. __iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
  1443. {
  1444. struct device *dev = iommu_group_first_dev(group);
  1445. struct iommu_domain *dom;
  1446. if (group->default_domain && group->default_domain->type == req_type)
  1447. return group->default_domain;
  1448. /*
  1449. * When allocating the DMA API domain assume that the driver is going to
  1450. * use PASID and make sure the RID's domain is PASID compatible.
  1451. */
  1452. if (req_type & __IOMMU_DOMAIN_PAGING) {
  1453. dom = __iommu_paging_domain_alloc_flags(dev, req_type,
  1454. dev->iommu->max_pasids ? IOMMU_HWPT_ALLOC_PASID : 0);
  1455. /*
  1456. * If driver does not support PASID feature then
  1457. * try to allocate non-PASID domain
  1458. */
  1459. if (PTR_ERR(dom) == -EOPNOTSUPP)
  1460. dom = __iommu_paging_domain_alloc_flags(dev, req_type, 0);
  1461. return dom;
  1462. }
  1463. if (req_type == IOMMU_DOMAIN_IDENTITY)
  1464. return __iommu_alloc_identity_domain(dev);
  1465. return ERR_PTR(-EINVAL);
  1466. }
  1467. /*
  1468. * req_type of 0 means "auto" which means to select a domain based on
  1469. * iommu_def_domain_type or what the driver actually supports.
  1470. */
  1471. static struct iommu_domain *
  1472. iommu_group_alloc_default_domain(struct iommu_group *group, int req_type)
  1473. {
  1474. const struct iommu_ops *ops = dev_iommu_ops(iommu_group_first_dev(group));
  1475. struct iommu_domain *dom;
  1476. lockdep_assert_held(&group->mutex);
  1477. /*
  1478. * Allow legacy drivers to specify the domain that will be the default
  1479. * domain. This should always be either an IDENTITY/BLOCKED/PLATFORM
  1480. * domain. Do not use in new drivers.
  1481. */
  1482. if (ops->default_domain) {
  1483. if (req_type != ops->default_domain->type)
  1484. return ERR_PTR(-EINVAL);
  1485. return ops->default_domain;
  1486. }
  1487. if (req_type)
  1488. return __iommu_group_alloc_default_domain(group, req_type);
  1489. /* The driver gave no guidance on what type to use, try the default */
  1490. dom = __iommu_group_alloc_default_domain(group, iommu_def_domain_type);
  1491. if (!IS_ERR(dom))
  1492. return dom;
  1493. /* Otherwise IDENTITY and DMA_FQ defaults will try DMA */
  1494. if (iommu_def_domain_type == IOMMU_DOMAIN_DMA)
  1495. return ERR_PTR(-EINVAL);
  1496. dom = __iommu_group_alloc_default_domain(group, IOMMU_DOMAIN_DMA);
  1497. if (IS_ERR(dom))
  1498. return dom;
  1499. pr_warn("Failed to allocate default IOMMU domain of type %u for group %s - Falling back to IOMMU_DOMAIN_DMA",
  1500. iommu_def_domain_type, group->name);
  1501. return dom;
  1502. }
  1503. struct iommu_domain *iommu_group_default_domain(struct iommu_group *group)
  1504. {
  1505. return group->default_domain;
  1506. }
  1507. static int probe_iommu_group(struct device *dev, void *data)
  1508. {
  1509. struct list_head *group_list = data;
  1510. int ret;
  1511. mutex_lock(&iommu_probe_device_lock);
  1512. ret = __iommu_probe_device(dev, group_list);
  1513. mutex_unlock(&iommu_probe_device_lock);
  1514. if (ret == -ENODEV)
  1515. ret = 0;
  1516. return ret;
  1517. }
  1518. static int iommu_bus_notifier(struct notifier_block *nb,
  1519. unsigned long action, void *data)
  1520. {
  1521. struct device *dev = data;
  1522. if (action == BUS_NOTIFY_ADD_DEVICE) {
  1523. int ret;
  1524. ret = iommu_probe_device(dev);
  1525. return (ret) ? NOTIFY_DONE : NOTIFY_OK;
  1526. } else if (action == BUS_NOTIFY_REMOVED_DEVICE) {
  1527. iommu_release_device(dev);
  1528. return NOTIFY_OK;
  1529. }
  1530. return 0;
  1531. }
  1532. /*
  1533. * Combine the driver's chosen def_domain_type across all the devices in a
  1534. * group. Drivers must give a consistent result.
  1535. */
  1536. static int iommu_get_def_domain_type(struct iommu_group *group,
  1537. struct device *dev, int cur_type)
  1538. {
  1539. const struct iommu_ops *ops = dev_iommu_ops(dev);
  1540. int type;
  1541. if (ops->default_domain) {
  1542. /*
  1543. * Drivers that declare a global static default_domain will
  1544. * always choose that.
  1545. */
  1546. type = ops->default_domain->type;
  1547. } else {
  1548. if (ops->def_domain_type)
  1549. type = ops->def_domain_type(dev);
  1550. else
  1551. return cur_type;
  1552. }
  1553. if (!type || cur_type == type)
  1554. return cur_type;
  1555. if (!cur_type)
  1556. return type;
  1557. dev_err_ratelimited(
  1558. dev,
  1559. "IOMMU driver error, requesting conflicting def_domain_type, %s and %s, for devices in group %u.\n",
  1560. iommu_domain_type_str(cur_type), iommu_domain_type_str(type),
  1561. group->id);
  1562. /*
  1563. * Try to recover, drivers are allowed to force IDENTITY or DMA, IDENTITY
  1564. * takes precedence.
  1565. */
  1566. if (type == IOMMU_DOMAIN_IDENTITY)
  1567. return type;
  1568. return cur_type;
  1569. }
  1570. /*
  1571. * A target_type of 0 will select the best domain type. 0 can be returned in
  1572. * this case meaning the global default should be used.
  1573. */
  1574. static int iommu_get_default_domain_type(struct iommu_group *group,
  1575. int target_type)
  1576. {
  1577. struct device *untrusted = NULL;
  1578. struct group_device *gdev;
  1579. int driver_type = 0;
  1580. lockdep_assert_held(&group->mutex);
  1581. /*
  1582. * ARM32 drivers supporting CONFIG_ARM_DMA_USE_IOMMU can declare an
  1583. * identity_domain and it will automatically become their default
  1584. * domain. Later on ARM_DMA_USE_IOMMU will install its UNMANAGED domain.
  1585. * Override the selection to IDENTITY.
  1586. */
  1587. if (IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU)) {
  1588. static_assert(!(IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU) &&
  1589. IS_ENABLED(CONFIG_IOMMU_DMA)));
  1590. driver_type = IOMMU_DOMAIN_IDENTITY;
  1591. }
  1592. for_each_group_device(group, gdev) {
  1593. driver_type = iommu_get_def_domain_type(group, gdev->dev,
  1594. driver_type);
  1595. if (dev_is_pci(gdev->dev) && to_pci_dev(gdev->dev)->untrusted) {
  1596. /*
  1597. * No ARM32 using systems will set untrusted, it cannot
  1598. * work.
  1599. */
  1600. if (WARN_ON(IS_ENABLED(CONFIG_ARM_DMA_USE_IOMMU)))
  1601. return -1;
  1602. untrusted = gdev->dev;
  1603. }
  1604. }
  1605. /*
  1606. * If the common dma ops are not selected in kconfig then we cannot use
  1607. * IOMMU_DOMAIN_DMA at all. Force IDENTITY if nothing else has been
  1608. * selected.
  1609. */
  1610. if (!IS_ENABLED(CONFIG_IOMMU_DMA)) {
  1611. if (WARN_ON(driver_type == IOMMU_DOMAIN_DMA))
  1612. return -1;
  1613. if (!driver_type)
  1614. driver_type = IOMMU_DOMAIN_IDENTITY;
  1615. }
  1616. if (untrusted) {
  1617. if (driver_type && driver_type != IOMMU_DOMAIN_DMA) {
  1618. dev_err_ratelimited(
  1619. untrusted,
  1620. "Device is not trusted, but driver is overriding group %u to %s, refusing to probe.\n",
  1621. group->id, iommu_domain_type_str(driver_type));
  1622. return -1;
  1623. }
  1624. driver_type = IOMMU_DOMAIN_DMA;
  1625. }
  1626. if (target_type) {
  1627. if (driver_type && target_type != driver_type)
  1628. return -1;
  1629. return target_type;
  1630. }
  1631. return driver_type;
  1632. }
  1633. static void iommu_group_do_probe_finalize(struct device *dev)
  1634. {
  1635. const struct iommu_ops *ops = dev_iommu_ops(dev);
  1636. if (ops->probe_finalize)
  1637. ops->probe_finalize(dev);
  1638. }
  1639. static int bus_iommu_probe(const struct bus_type *bus)
  1640. {
  1641. struct iommu_group *group, *next;
  1642. LIST_HEAD(group_list);
  1643. int ret;
  1644. ret = bus_for_each_dev(bus, NULL, &group_list, probe_iommu_group);
  1645. if (ret)
  1646. return ret;
  1647. list_for_each_entry_safe(group, next, &group_list, entry) {
  1648. struct group_device *gdev;
  1649. mutex_lock(&group->mutex);
  1650. /* Remove item from the list */
  1651. list_del_init(&group->entry);
  1652. /*
  1653. * We go to the trouble of deferred default domain creation so
  1654. * that the cross-group default domain type and the setup of the
  1655. * IOMMU_RESV_DIRECT will work correctly in non-hotpug scenarios.
  1656. */
  1657. ret = iommu_setup_default_domain(group, 0);
  1658. if (ret) {
  1659. mutex_unlock(&group->mutex);
  1660. return ret;
  1661. }
  1662. for_each_group_device(group, gdev)
  1663. iommu_setup_dma_ops(gdev->dev, group->default_domain);
  1664. mutex_unlock(&group->mutex);
  1665. /*
  1666. * FIXME: Mis-locked because the ops->probe_finalize() call-back
  1667. * of some IOMMU drivers calls arm_iommu_attach_device() which
  1668. * in-turn might call back into IOMMU core code, where it tries
  1669. * to take group->mutex, resulting in a deadlock.
  1670. */
  1671. for_each_group_device(group, gdev)
  1672. iommu_group_do_probe_finalize(gdev->dev);
  1673. }
  1674. return 0;
  1675. }
  1676. /**
  1677. * device_iommu_capable() - check for a general IOMMU capability
  1678. * @dev: device to which the capability would be relevant, if available
  1679. * @cap: IOMMU capability
  1680. *
  1681. * Return: true if an IOMMU is present and supports the given capability
  1682. * for the given device, otherwise false.
  1683. */
  1684. bool device_iommu_capable(struct device *dev, enum iommu_cap cap)
  1685. {
  1686. const struct iommu_ops *ops;
  1687. if (!dev_has_iommu(dev))
  1688. return false;
  1689. ops = dev_iommu_ops(dev);
  1690. if (!ops->capable)
  1691. return false;
  1692. return ops->capable(dev, cap);
  1693. }
  1694. EXPORT_SYMBOL_GPL(device_iommu_capable);
  1695. /**
  1696. * iommu_group_has_isolated_msi() - Compute msi_device_has_isolated_msi()
  1697. * for a group
  1698. * @group: Group to query
  1699. *
  1700. * IOMMU groups should not have differing values of
  1701. * msi_device_has_isolated_msi() for devices in a group. However nothing
  1702. * directly prevents this, so ensure mistakes don't result in isolation failures
  1703. * by checking that all the devices are the same.
  1704. */
  1705. bool iommu_group_has_isolated_msi(struct iommu_group *group)
  1706. {
  1707. struct group_device *group_dev;
  1708. bool ret = true;
  1709. mutex_lock(&group->mutex);
  1710. for_each_group_device(group, group_dev)
  1711. ret &= msi_device_has_isolated_msi(group_dev->dev);
  1712. mutex_unlock(&group->mutex);
  1713. return ret;
  1714. }
  1715. EXPORT_SYMBOL_GPL(iommu_group_has_isolated_msi);
  1716. /**
  1717. * iommu_set_fault_handler() - set a fault handler for an iommu domain
  1718. * @domain: iommu domain
  1719. * @handler: fault handler
  1720. * @token: user data, will be passed back to the fault handler
  1721. *
  1722. * This function should be used by IOMMU users which want to be notified
  1723. * whenever an IOMMU fault happens.
  1724. *
  1725. * The fault handler itself should return 0 on success, and an appropriate
  1726. * error code otherwise.
  1727. */
  1728. void iommu_set_fault_handler(struct iommu_domain *domain,
  1729. iommu_fault_handler_t handler,
  1730. void *token)
  1731. {
  1732. if (WARN_ON(!domain || domain->cookie_type != IOMMU_COOKIE_NONE))
  1733. return;
  1734. domain->cookie_type = IOMMU_COOKIE_FAULT_HANDLER;
  1735. domain->handler = handler;
  1736. domain->handler_token = token;
  1737. }
  1738. EXPORT_SYMBOL_GPL(iommu_set_fault_handler);
  1739. static void iommu_domain_init(struct iommu_domain *domain, unsigned int type,
  1740. const struct iommu_ops *ops)
  1741. {
  1742. domain->type = type;
  1743. domain->owner = ops;
  1744. if (!domain->ops)
  1745. domain->ops = ops->default_domain_ops;
  1746. }
  1747. static struct iommu_domain *
  1748. __iommu_paging_domain_alloc_flags(struct device *dev, unsigned int type,
  1749. unsigned int flags)
  1750. {
  1751. const struct iommu_ops *ops;
  1752. struct iommu_domain *domain;
  1753. if (!dev_has_iommu(dev))
  1754. return ERR_PTR(-ENODEV);
  1755. ops = dev_iommu_ops(dev);
  1756. if (ops->domain_alloc_paging && !flags)
  1757. domain = ops->domain_alloc_paging(dev);
  1758. else if (ops->domain_alloc_paging_flags)
  1759. domain = ops->domain_alloc_paging_flags(dev, flags, NULL);
  1760. #if IS_ENABLED(CONFIG_FSL_PAMU)
  1761. else if (ops->domain_alloc && !flags)
  1762. domain = ops->domain_alloc(IOMMU_DOMAIN_UNMANAGED);
  1763. #endif
  1764. else
  1765. return ERR_PTR(-EOPNOTSUPP);
  1766. if (IS_ERR(domain))
  1767. return domain;
  1768. if (!domain)
  1769. return ERR_PTR(-ENOMEM);
  1770. iommu_domain_init(domain, type, ops);
  1771. return domain;
  1772. }
  1773. /**
  1774. * iommu_paging_domain_alloc_flags() - Allocate a paging domain
  1775. * @dev: device for which the domain is allocated
  1776. * @flags: Bitmap of iommufd_hwpt_alloc_flags
  1777. *
  1778. * Allocate a paging domain which will be managed by a kernel driver. Return
  1779. * allocated domain if successful, or an ERR pointer for failure.
  1780. */
  1781. struct iommu_domain *iommu_paging_domain_alloc_flags(struct device *dev,
  1782. unsigned int flags)
  1783. {
  1784. return __iommu_paging_domain_alloc_flags(dev,
  1785. IOMMU_DOMAIN_UNMANAGED, flags);
  1786. }
  1787. EXPORT_SYMBOL_GPL(iommu_paging_domain_alloc_flags);
  1788. void iommu_domain_free(struct iommu_domain *domain)
  1789. {
  1790. switch (domain->cookie_type) {
  1791. case IOMMU_COOKIE_DMA_IOVA:
  1792. iommu_put_dma_cookie(domain);
  1793. break;
  1794. case IOMMU_COOKIE_DMA_MSI:
  1795. iommu_put_msi_cookie(domain);
  1796. break;
  1797. case IOMMU_COOKIE_SVA:
  1798. mmdrop(domain->mm);
  1799. break;
  1800. default:
  1801. break;
  1802. }
  1803. if (domain->ops->free)
  1804. domain->ops->free(domain);
  1805. }
  1806. EXPORT_SYMBOL_GPL(iommu_domain_free);
  1807. /*
  1808. * Put the group's domain back to the appropriate core-owned domain - either the
  1809. * standard kernel-mode DMA configuration or an all-DMA-blocked domain.
  1810. */
  1811. static void __iommu_group_set_core_domain(struct iommu_group *group)
  1812. {
  1813. struct iommu_domain *new_domain;
  1814. if (group->owner)
  1815. new_domain = group->blocking_domain;
  1816. else
  1817. new_domain = group->default_domain;
  1818. __iommu_group_set_domain_nofail(group, new_domain);
  1819. }
  1820. static int __iommu_attach_device(struct iommu_domain *domain,
  1821. struct device *dev, struct iommu_domain *old)
  1822. {
  1823. int ret;
  1824. if (unlikely(domain->ops->attach_dev == NULL))
  1825. return -ENODEV;
  1826. ret = domain->ops->attach_dev(domain, dev, old);
  1827. if (ret)
  1828. return ret;
  1829. dev->iommu->attach_deferred = 0;
  1830. trace_attach_device_to_domain(dev);
  1831. return 0;
  1832. }
  1833. /**
  1834. * iommu_attach_device - Attach an IOMMU domain to a device
  1835. * @domain: IOMMU domain to attach
  1836. * @dev: Device that will be attached
  1837. *
  1838. * Returns 0 on success and error code on failure
  1839. *
  1840. * Note that EINVAL can be treated as a soft failure, indicating
  1841. * that certain configuration of the domain is incompatible with
  1842. * the device. In this case attaching a different domain to the
  1843. * device may succeed.
  1844. */
  1845. int iommu_attach_device(struct iommu_domain *domain, struct device *dev)
  1846. {
  1847. /* Caller must be a probed driver on dev */
  1848. struct iommu_group *group = dev->iommu_group;
  1849. int ret;
  1850. if (!group)
  1851. return -ENODEV;
  1852. /*
  1853. * Lock the group to make sure the device-count doesn't
  1854. * change while we are attaching
  1855. */
  1856. mutex_lock(&group->mutex);
  1857. ret = -EINVAL;
  1858. if (list_count_nodes(&group->devices) != 1)
  1859. goto out_unlock;
  1860. ret = __iommu_attach_group(domain, group);
  1861. out_unlock:
  1862. mutex_unlock(&group->mutex);
  1863. return ret;
  1864. }
  1865. EXPORT_SYMBOL_GPL(iommu_attach_device);
  1866. int iommu_deferred_attach(struct device *dev, struct iommu_domain *domain)
  1867. {
  1868. /*
  1869. * This is called on the dma mapping fast path so avoid locking. This is
  1870. * racy, but we have an expectation that the driver will setup its DMAs
  1871. * inside probe while being single threaded to avoid racing.
  1872. */
  1873. if (!dev->iommu || !dev->iommu->attach_deferred)
  1874. return 0;
  1875. guard(mutex)(&dev->iommu_group->mutex);
  1876. /*
  1877. * This is a concurrent attach during a device reset. Reject it until
  1878. * pci_dev_reset_iommu_done() attaches the device to group->domain.
  1879. *
  1880. * Note that this might fail the iommu_dma_map(). But there's nothing
  1881. * more we can do here.
  1882. */
  1883. if (dev->iommu_group->resetting_domain)
  1884. return -EBUSY;
  1885. return __iommu_attach_device(domain, dev, NULL);
  1886. }
  1887. void iommu_detach_device(struct iommu_domain *domain, struct device *dev)
  1888. {
  1889. /* Caller must be a probed driver on dev */
  1890. struct iommu_group *group = dev->iommu_group;
  1891. if (!group)
  1892. return;
  1893. mutex_lock(&group->mutex);
  1894. if (WARN_ON(domain != group->domain) ||
  1895. WARN_ON(list_count_nodes(&group->devices) != 1))
  1896. goto out_unlock;
  1897. __iommu_group_set_core_domain(group);
  1898. out_unlock:
  1899. mutex_unlock(&group->mutex);
  1900. }
  1901. EXPORT_SYMBOL_GPL(iommu_detach_device);
  1902. /**
  1903. * iommu_get_domain_for_dev() - Return the DMA API domain pointer
  1904. * @dev: Device to query
  1905. *
  1906. * This function can be called within a driver bound to dev. The returned
  1907. * pointer is valid for the lifetime of the bound driver.
  1908. *
  1909. * It should not be called by drivers with driver_managed_dma = true.
  1910. */
  1911. struct iommu_domain *iommu_get_domain_for_dev(struct device *dev)
  1912. {
  1913. /* Caller must be a probed driver on dev */
  1914. struct iommu_group *group = dev->iommu_group;
  1915. if (!group)
  1916. return NULL;
  1917. lockdep_assert_not_held(&group->mutex);
  1918. return group->domain;
  1919. }
  1920. EXPORT_SYMBOL_GPL(iommu_get_domain_for_dev);
  1921. /**
  1922. * iommu_driver_get_domain_for_dev() - Return the driver-level domain pointer
  1923. * @dev: Device to query
  1924. *
  1925. * This function can be called by an iommu driver that wants to get the physical
  1926. * domain within an iommu callback function where group->mutex is held.
  1927. */
  1928. struct iommu_domain *iommu_driver_get_domain_for_dev(struct device *dev)
  1929. {
  1930. struct iommu_group *group = dev->iommu_group;
  1931. lockdep_assert_held(&group->mutex);
  1932. /*
  1933. * Driver handles the low-level __iommu_attach_device(), including the
  1934. * one invoked by pci_dev_reset_iommu_done() re-attaching the device to
  1935. * the cached group->domain. In this case, the driver must get the old
  1936. * domain from group->resetting_domain rather than group->domain. This
  1937. * prevents it from re-attaching the device from group->domain (old) to
  1938. * group->domain (new).
  1939. */
  1940. if (group->resetting_domain)
  1941. return group->resetting_domain;
  1942. return group->domain;
  1943. }
  1944. EXPORT_SYMBOL_GPL(iommu_driver_get_domain_for_dev);
  1945. /*
  1946. * For IOMMU_DOMAIN_DMA implementations which already provide their own
  1947. * guarantees that the group and its default domain are valid and correct.
  1948. */
  1949. struct iommu_domain *iommu_get_dma_domain(struct device *dev)
  1950. {
  1951. return dev->iommu_group->default_domain;
  1952. }
  1953. static void *iommu_make_pasid_array_entry(struct iommu_domain *domain,
  1954. struct iommu_attach_handle *handle)
  1955. {
  1956. if (handle) {
  1957. handle->domain = domain;
  1958. return xa_tag_pointer(handle, IOMMU_PASID_ARRAY_HANDLE);
  1959. }
  1960. return xa_tag_pointer(domain, IOMMU_PASID_ARRAY_DOMAIN);
  1961. }
  1962. static bool domain_iommu_ops_compatible(const struct iommu_ops *ops,
  1963. struct iommu_domain *domain)
  1964. {
  1965. if (domain->owner == ops)
  1966. return true;
  1967. /* For static domains, owner isn't set. */
  1968. if (domain == ops->blocked_domain || domain == ops->identity_domain)
  1969. return true;
  1970. return false;
  1971. }
  1972. static int __iommu_attach_group(struct iommu_domain *domain,
  1973. struct iommu_group *group)
  1974. {
  1975. struct device *dev;
  1976. if (group->domain && group->domain != group->default_domain &&
  1977. group->domain != group->blocking_domain)
  1978. return -EBUSY;
  1979. dev = iommu_group_first_dev(group);
  1980. if (!dev_has_iommu(dev) ||
  1981. !domain_iommu_ops_compatible(dev_iommu_ops(dev), domain))
  1982. return -EINVAL;
  1983. return __iommu_group_set_domain(group, domain);
  1984. }
  1985. /**
  1986. * iommu_attach_group - Attach an IOMMU domain to an IOMMU group
  1987. * @domain: IOMMU domain to attach
  1988. * @group: IOMMU group that will be attached
  1989. *
  1990. * Returns 0 on success and error code on failure
  1991. *
  1992. * Note that EINVAL can be treated as a soft failure, indicating
  1993. * that certain configuration of the domain is incompatible with
  1994. * the group. In this case attaching a different domain to the
  1995. * group may succeed.
  1996. */
  1997. int iommu_attach_group(struct iommu_domain *domain, struct iommu_group *group)
  1998. {
  1999. int ret;
  2000. mutex_lock(&group->mutex);
  2001. ret = __iommu_attach_group(domain, group);
  2002. mutex_unlock(&group->mutex);
  2003. return ret;
  2004. }
  2005. EXPORT_SYMBOL_GPL(iommu_attach_group);
  2006. static int __iommu_device_set_domain(struct iommu_group *group,
  2007. struct device *dev,
  2008. struct iommu_domain *new_domain,
  2009. struct iommu_domain *old_domain,
  2010. unsigned int flags)
  2011. {
  2012. int ret;
  2013. /*
  2014. * If the device requires IOMMU_RESV_DIRECT then we cannot allow
  2015. * the blocking domain to be attached as it does not contain the
  2016. * required 1:1 mapping. This test effectively excludes the device
  2017. * being used with iommu_group_claim_dma_owner() which will block
  2018. * vfio and iommufd as well.
  2019. */
  2020. if (dev->iommu->require_direct &&
  2021. (new_domain->type == IOMMU_DOMAIN_BLOCKED ||
  2022. new_domain == group->blocking_domain)) {
  2023. dev_warn(dev,
  2024. "Firmware has requested this device have a 1:1 IOMMU mapping, rejecting configuring the device without a 1:1 mapping. Contact your platform vendor.\n");
  2025. return -EINVAL;
  2026. }
  2027. if (dev->iommu->attach_deferred) {
  2028. if (new_domain == group->default_domain)
  2029. return 0;
  2030. dev->iommu->attach_deferred = 0;
  2031. }
  2032. ret = __iommu_attach_device(new_domain, dev, old_domain);
  2033. if (ret) {
  2034. /*
  2035. * If we have a blocking domain then try to attach that in hopes
  2036. * of avoiding a UAF. Modern drivers should implement blocking
  2037. * domains as global statics that cannot fail.
  2038. */
  2039. if ((flags & IOMMU_SET_DOMAIN_MUST_SUCCEED) &&
  2040. group->blocking_domain &&
  2041. group->blocking_domain != new_domain)
  2042. __iommu_attach_device(group->blocking_domain, dev,
  2043. old_domain);
  2044. return ret;
  2045. }
  2046. return 0;
  2047. }
  2048. /*
  2049. * If 0 is returned the group's domain is new_domain. If an error is returned
  2050. * then the group's domain will be set back to the existing domain unless
  2051. * IOMMU_SET_DOMAIN_MUST_SUCCEED, otherwise an error is returned and the group's
  2052. * domains is left inconsistent. This is a driver bug to fail attach with a
  2053. * previously good domain. We try to avoid a kernel UAF because of this.
  2054. *
  2055. * IOMMU groups are really the natural working unit of the IOMMU, but the IOMMU
  2056. * API works on domains and devices. Bridge that gap by iterating over the
  2057. * devices in a group. Ideally we'd have a single device which represents the
  2058. * requestor ID of the group, but we also allow IOMMU drivers to create policy
  2059. * defined minimum sets, where the physical hardware may be able to distiguish
  2060. * members, but we wish to group them at a higher level (ex. untrusted
  2061. * multi-function PCI devices). Thus we attach each device.
  2062. */
  2063. static int __iommu_group_set_domain_internal(struct iommu_group *group,
  2064. struct iommu_domain *new_domain,
  2065. unsigned int flags)
  2066. {
  2067. struct group_device *last_gdev;
  2068. struct group_device *gdev;
  2069. int result;
  2070. int ret;
  2071. lockdep_assert_held(&group->mutex);
  2072. if (group->domain == new_domain)
  2073. return 0;
  2074. if (WARN_ON(!new_domain))
  2075. return -EINVAL;
  2076. /*
  2077. * This is a concurrent attach during a device reset. Reject it until
  2078. * pci_dev_reset_iommu_done() attaches the device to group->domain.
  2079. */
  2080. if (group->resetting_domain)
  2081. return -EBUSY;
  2082. /*
  2083. * Changing the domain is done by calling attach_dev() on the new
  2084. * domain. This switch does not have to be atomic and DMA can be
  2085. * discarded during the transition. DMA must only be able to access
  2086. * either new_domain or group->domain, never something else.
  2087. */
  2088. result = 0;
  2089. for_each_group_device(group, gdev) {
  2090. ret = __iommu_device_set_domain(group, gdev->dev, new_domain,
  2091. group->domain, flags);
  2092. if (ret) {
  2093. result = ret;
  2094. /*
  2095. * Keep trying the other devices in the group. If a
  2096. * driver fails attach to an otherwise good domain, and
  2097. * does not support blocking domains, it should at least
  2098. * drop its reference on the current domain so we don't
  2099. * UAF.
  2100. */
  2101. if (flags & IOMMU_SET_DOMAIN_MUST_SUCCEED)
  2102. continue;
  2103. goto err_revert;
  2104. }
  2105. }
  2106. group->domain = new_domain;
  2107. return result;
  2108. err_revert:
  2109. /*
  2110. * This is called in error unwind paths. A well behaved driver should
  2111. * always allow us to attach to a domain that was already attached.
  2112. */
  2113. last_gdev = gdev;
  2114. for_each_group_device(group, gdev) {
  2115. /* No need to revert the last gdev that failed to set domain */
  2116. if (gdev == last_gdev)
  2117. break;
  2118. /*
  2119. * A NULL domain can happen only for first probe, in which case
  2120. * we leave group->domain as NULL and let release clean
  2121. * everything up.
  2122. */
  2123. if (group->domain)
  2124. WARN_ON(__iommu_device_set_domain(
  2125. group, gdev->dev, group->domain, new_domain,
  2126. IOMMU_SET_DOMAIN_MUST_SUCCEED));
  2127. }
  2128. return ret;
  2129. }
  2130. void iommu_detach_group(struct iommu_domain *domain, struct iommu_group *group)
  2131. {
  2132. mutex_lock(&group->mutex);
  2133. __iommu_group_set_core_domain(group);
  2134. mutex_unlock(&group->mutex);
  2135. }
  2136. EXPORT_SYMBOL_GPL(iommu_detach_group);
  2137. phys_addr_t iommu_iova_to_phys(struct iommu_domain *domain, dma_addr_t iova)
  2138. {
  2139. if (domain->type == IOMMU_DOMAIN_IDENTITY)
  2140. return iova;
  2141. if (domain->type == IOMMU_DOMAIN_BLOCKED)
  2142. return 0;
  2143. return domain->ops->iova_to_phys(domain, iova);
  2144. }
  2145. EXPORT_SYMBOL_GPL(iommu_iova_to_phys);
  2146. static size_t iommu_pgsize(struct iommu_domain *domain, unsigned long iova,
  2147. phys_addr_t paddr, size_t size, size_t *count)
  2148. {
  2149. unsigned int pgsize_idx, pgsize_idx_next;
  2150. unsigned long pgsizes;
  2151. size_t offset, pgsize, pgsize_next;
  2152. size_t offset_end;
  2153. unsigned long addr_merge = paddr | iova;
  2154. /* Page sizes supported by the hardware and small enough for @size */
  2155. pgsizes = domain->pgsize_bitmap & GENMASK(__fls(size), 0);
  2156. /* Constrain the page sizes further based on the maximum alignment */
  2157. if (likely(addr_merge))
  2158. pgsizes &= GENMASK(__ffs(addr_merge), 0);
  2159. /* Make sure we have at least one suitable page size */
  2160. BUG_ON(!pgsizes);
  2161. /* Pick the biggest page size remaining */
  2162. pgsize_idx = __fls(pgsizes);
  2163. pgsize = BIT(pgsize_idx);
  2164. if (!count)
  2165. return pgsize;
  2166. /* Find the next biggest support page size, if it exists */
  2167. pgsizes = domain->pgsize_bitmap & ~GENMASK(pgsize_idx, 0);
  2168. if (!pgsizes)
  2169. goto out_set_count;
  2170. pgsize_idx_next = __ffs(pgsizes);
  2171. pgsize_next = BIT(pgsize_idx_next);
  2172. /*
  2173. * There's no point trying a bigger page size unless the virtual
  2174. * and physical addresses are similarly offset within the larger page.
  2175. */
  2176. if ((iova ^ paddr) & (pgsize_next - 1))
  2177. goto out_set_count;
  2178. /* Calculate the offset to the next page size alignment boundary */
  2179. offset = pgsize_next - (addr_merge & (pgsize_next - 1));
  2180. /*
  2181. * If size is big enough to accommodate the larger page, reduce
  2182. * the number of smaller pages.
  2183. */
  2184. if (!check_add_overflow(offset, pgsize_next, &offset_end) &&
  2185. offset_end <= size)
  2186. size = offset;
  2187. out_set_count:
  2188. *count = size >> pgsize_idx;
  2189. return pgsize;
  2190. }
  2191. int iommu_map_nosync(struct iommu_domain *domain, unsigned long iova,
  2192. phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
  2193. {
  2194. const struct iommu_domain_ops *ops = domain->ops;
  2195. unsigned long orig_iova = iova;
  2196. unsigned int min_pagesz;
  2197. size_t orig_size = size;
  2198. phys_addr_t orig_paddr = paddr;
  2199. int ret = 0;
  2200. might_sleep_if(gfpflags_allow_blocking(gfp));
  2201. if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
  2202. return -EINVAL;
  2203. if (WARN_ON(!ops->map_pages || domain->pgsize_bitmap == 0UL))
  2204. return -ENODEV;
  2205. /* Discourage passing strange GFP flags */
  2206. if (WARN_ON_ONCE(gfp & (__GFP_COMP | __GFP_DMA | __GFP_DMA32 |
  2207. __GFP_HIGHMEM)))
  2208. return -EINVAL;
  2209. /* find out the minimum page size supported */
  2210. min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
  2211. /*
  2212. * both the virtual address and the physical one, as well as
  2213. * the size of the mapping, must be aligned (at least) to the
  2214. * size of the smallest page supported by the hardware
  2215. */
  2216. if (!IS_ALIGNED(iova | paddr | size, min_pagesz)) {
  2217. pr_err("unaligned: iova 0x%lx pa %pa size 0x%zx min_pagesz 0x%x\n",
  2218. iova, &paddr, size, min_pagesz);
  2219. return -EINVAL;
  2220. }
  2221. pr_debug("map: iova 0x%lx pa %pa size 0x%zx\n", iova, &paddr, size);
  2222. while (size) {
  2223. size_t pgsize, count, mapped = 0;
  2224. pgsize = iommu_pgsize(domain, iova, paddr, size, &count);
  2225. pr_debug("mapping: iova 0x%lx pa %pa pgsize 0x%zx count %zu\n",
  2226. iova, &paddr, pgsize, count);
  2227. ret = ops->map_pages(domain, iova, paddr, pgsize, count, prot,
  2228. gfp, &mapped);
  2229. /*
  2230. * Some pages may have been mapped, even if an error occurred,
  2231. * so we should account for those so they can be unmapped.
  2232. */
  2233. size -= mapped;
  2234. if (ret)
  2235. break;
  2236. iova += mapped;
  2237. paddr += mapped;
  2238. }
  2239. /* unroll mapping in case something went wrong */
  2240. if (ret) {
  2241. iommu_unmap(domain, orig_iova, orig_size - size);
  2242. } else {
  2243. trace_map(orig_iova, orig_paddr, orig_size);
  2244. iommu_debug_map(domain, orig_paddr, orig_size);
  2245. }
  2246. return ret;
  2247. }
  2248. int iommu_sync_map(struct iommu_domain *domain, unsigned long iova, size_t size)
  2249. {
  2250. const struct iommu_domain_ops *ops = domain->ops;
  2251. if (!ops->iotlb_sync_map)
  2252. return 0;
  2253. return ops->iotlb_sync_map(domain, iova, size);
  2254. }
  2255. int iommu_map(struct iommu_domain *domain, unsigned long iova,
  2256. phys_addr_t paddr, size_t size, int prot, gfp_t gfp)
  2257. {
  2258. int ret;
  2259. ret = iommu_map_nosync(domain, iova, paddr, size, prot, gfp);
  2260. if (ret)
  2261. return ret;
  2262. ret = iommu_sync_map(domain, iova, size);
  2263. if (ret)
  2264. iommu_unmap(domain, iova, size);
  2265. return ret;
  2266. }
  2267. EXPORT_SYMBOL_GPL(iommu_map);
  2268. static size_t __iommu_unmap(struct iommu_domain *domain,
  2269. unsigned long iova, size_t size,
  2270. struct iommu_iotlb_gather *iotlb_gather)
  2271. {
  2272. const struct iommu_domain_ops *ops = domain->ops;
  2273. size_t unmapped_page, unmapped = 0;
  2274. unsigned long orig_iova = iova;
  2275. unsigned int min_pagesz;
  2276. if (unlikely(!(domain->type & __IOMMU_DOMAIN_PAGING)))
  2277. return 0;
  2278. if (WARN_ON(!ops->unmap_pages || domain->pgsize_bitmap == 0UL))
  2279. return 0;
  2280. /* find out the minimum page size supported */
  2281. min_pagesz = 1 << __ffs(domain->pgsize_bitmap);
  2282. /*
  2283. * The virtual address, as well as the size of the mapping, must be
  2284. * aligned (at least) to the size of the smallest page supported
  2285. * by the hardware
  2286. */
  2287. if (!IS_ALIGNED(iova | size, min_pagesz)) {
  2288. pr_err("unaligned: iova 0x%lx size 0x%zx min_pagesz 0x%x\n",
  2289. iova, size, min_pagesz);
  2290. return 0;
  2291. }
  2292. pr_debug("unmap this: iova 0x%lx size 0x%zx\n", iova, size);
  2293. iommu_debug_unmap_begin(domain, iova, size);
  2294. /*
  2295. * Keep iterating until we either unmap 'size' bytes (or more)
  2296. * or we hit an area that isn't mapped.
  2297. */
  2298. while (unmapped < size) {
  2299. size_t pgsize, count;
  2300. pgsize = iommu_pgsize(domain, iova, iova, size - unmapped, &count);
  2301. unmapped_page = ops->unmap_pages(domain, iova, pgsize, count, iotlb_gather);
  2302. if (!unmapped_page)
  2303. break;
  2304. pr_debug("unmapped: iova 0x%lx size 0x%zx\n",
  2305. iova, unmapped_page);
  2306. /*
  2307. * If the driver itself isn't using the gather, make sure
  2308. * it looks non-empty so iotlb_sync will still be called.
  2309. */
  2310. if (iotlb_gather->start >= iotlb_gather->end)
  2311. iommu_iotlb_gather_add_range(iotlb_gather, iova, size);
  2312. iova += unmapped_page;
  2313. unmapped += unmapped_page;
  2314. }
  2315. trace_unmap(orig_iova, size, unmapped);
  2316. iommu_debug_unmap_end(domain, orig_iova, size, unmapped);
  2317. return unmapped;
  2318. }
  2319. /**
  2320. * iommu_unmap() - Remove mappings from a range of IOVA
  2321. * @domain: Domain to manipulate
  2322. * @iova: IO virtual address to start
  2323. * @size: Length of the range starting from @iova
  2324. *
  2325. * iommu_unmap() will remove a translation created by iommu_map(). It cannot
  2326. * subdivide a mapping created by iommu_map(), so it should be called with IOVA
  2327. * ranges that match what was passed to iommu_map(). The range can aggregate
  2328. * contiguous iommu_map() calls so long as no individual range is split.
  2329. *
  2330. * Returns: Number of bytes of IOVA unmapped. iova + res will be the point
  2331. * unmapping stopped.
  2332. */
  2333. size_t iommu_unmap(struct iommu_domain *domain,
  2334. unsigned long iova, size_t size)
  2335. {
  2336. struct iommu_iotlb_gather iotlb_gather;
  2337. size_t ret;
  2338. iommu_iotlb_gather_init(&iotlb_gather);
  2339. ret = __iommu_unmap(domain, iova, size, &iotlb_gather);
  2340. iommu_iotlb_sync(domain, &iotlb_gather);
  2341. return ret;
  2342. }
  2343. EXPORT_SYMBOL_GPL(iommu_unmap);
  2344. /**
  2345. * iommu_unmap_fast() - Remove mappings from a range of IOVA without IOTLB sync
  2346. * @domain: Domain to manipulate
  2347. * @iova: IO virtual address to start
  2348. * @size: Length of the range starting from @iova
  2349. * @iotlb_gather: range information for a pending IOTLB flush
  2350. *
  2351. * iommu_unmap_fast() will remove a translation created by iommu_map().
  2352. * It can't subdivide a mapping created by iommu_map(), so it should be
  2353. * called with IOVA ranges that match what was passed to iommu_map(). The
  2354. * range can aggregate contiguous iommu_map() calls so long as no individual
  2355. * range is split.
  2356. *
  2357. * Basically iommu_unmap_fast() is the same as iommu_unmap() but for callers
  2358. * which manage the IOTLB flushing externally to perform a batched sync.
  2359. *
  2360. * Returns: Number of bytes of IOVA unmapped. iova + res will be the point
  2361. * unmapping stopped.
  2362. */
  2363. size_t iommu_unmap_fast(struct iommu_domain *domain,
  2364. unsigned long iova, size_t size,
  2365. struct iommu_iotlb_gather *iotlb_gather)
  2366. {
  2367. return __iommu_unmap(domain, iova, size, iotlb_gather);
  2368. }
  2369. EXPORT_SYMBOL_GPL(iommu_unmap_fast);
  2370. ssize_t iommu_map_sg(struct iommu_domain *domain, unsigned long iova,
  2371. struct scatterlist *sg, unsigned int nents, int prot,
  2372. gfp_t gfp)
  2373. {
  2374. size_t len = 0, mapped = 0;
  2375. phys_addr_t start;
  2376. unsigned int i = 0;
  2377. int ret;
  2378. while (i <= nents) {
  2379. phys_addr_t s_phys = sg_phys(sg);
  2380. if (len && s_phys != start + len) {
  2381. ret = iommu_map_nosync(domain, iova + mapped, start,
  2382. len, prot, gfp);
  2383. if (ret)
  2384. goto out_err;
  2385. mapped += len;
  2386. len = 0;
  2387. }
  2388. if (sg_dma_is_bus_address(sg))
  2389. goto next;
  2390. if (len) {
  2391. len += sg->length;
  2392. } else {
  2393. len = sg->length;
  2394. start = s_phys;
  2395. }
  2396. next:
  2397. if (++i < nents)
  2398. sg = sg_next(sg);
  2399. }
  2400. ret = iommu_sync_map(domain, iova, mapped);
  2401. if (ret)
  2402. goto out_err;
  2403. return mapped;
  2404. out_err:
  2405. /* undo mappings already done */
  2406. iommu_unmap(domain, iova, mapped);
  2407. return ret;
  2408. }
  2409. EXPORT_SYMBOL_GPL(iommu_map_sg);
  2410. /**
  2411. * report_iommu_fault() - report about an IOMMU fault to the IOMMU framework
  2412. * @domain: the iommu domain where the fault has happened
  2413. * @dev: the device where the fault has happened
  2414. * @iova: the faulting address
  2415. * @flags: mmu fault flags (e.g. IOMMU_FAULT_READ/IOMMU_FAULT_WRITE/...)
  2416. *
  2417. * This function should be called by the low-level IOMMU implementations
  2418. * whenever IOMMU faults happen, to allow high-level users, that are
  2419. * interested in such events, to know about them.
  2420. *
  2421. * This event may be useful for several possible use cases:
  2422. * - mere logging of the event
  2423. * - dynamic TLB/PTE loading
  2424. * - if restarting of the faulting device is required
  2425. *
  2426. * Returns 0 on success and an appropriate error code otherwise (if dynamic
  2427. * PTE/TLB loading will one day be supported, implementations will be able
  2428. * to tell whether it succeeded or not according to this return value).
  2429. *
  2430. * Specifically, -ENOSYS is returned if a fault handler isn't installed
  2431. * (though fault handlers can also return -ENOSYS, in case they want to
  2432. * elicit the default behavior of the IOMMU drivers).
  2433. */
  2434. int report_iommu_fault(struct iommu_domain *domain, struct device *dev,
  2435. unsigned long iova, int flags)
  2436. {
  2437. int ret = -ENOSYS;
  2438. /*
  2439. * if upper layers showed interest and installed a fault handler,
  2440. * invoke it.
  2441. */
  2442. if (domain->cookie_type == IOMMU_COOKIE_FAULT_HANDLER &&
  2443. domain->handler)
  2444. ret = domain->handler(domain, dev, iova, flags,
  2445. domain->handler_token);
  2446. trace_io_page_fault(dev, iova, flags);
  2447. return ret;
  2448. }
  2449. EXPORT_SYMBOL_GPL(report_iommu_fault);
  2450. static int __init iommu_init(void)
  2451. {
  2452. iommu_group_kset = kset_create_and_add("iommu_groups",
  2453. NULL, kernel_kobj);
  2454. BUG_ON(!iommu_group_kset);
  2455. iommu_debugfs_setup();
  2456. return 0;
  2457. }
  2458. core_initcall(iommu_init);
  2459. int iommu_set_pgtable_quirks(struct iommu_domain *domain,
  2460. unsigned long quirk)
  2461. {
  2462. if (domain->type != IOMMU_DOMAIN_UNMANAGED)
  2463. return -EINVAL;
  2464. if (!domain->ops->set_pgtable_quirks)
  2465. return -EINVAL;
  2466. return domain->ops->set_pgtable_quirks(domain, quirk);
  2467. }
  2468. EXPORT_SYMBOL_GPL(iommu_set_pgtable_quirks);
  2469. /**
  2470. * iommu_get_resv_regions - get reserved regions
  2471. * @dev: device for which to get reserved regions
  2472. * @list: reserved region list for device
  2473. *
  2474. * This returns a list of reserved IOVA regions specific to this device.
  2475. * A domain user should not map IOVA in these ranges.
  2476. */
  2477. void iommu_get_resv_regions(struct device *dev, struct list_head *list)
  2478. {
  2479. const struct iommu_ops *ops = dev_iommu_ops(dev);
  2480. if (ops->get_resv_regions)
  2481. ops->get_resv_regions(dev, list);
  2482. }
  2483. EXPORT_SYMBOL_GPL(iommu_get_resv_regions);
  2484. /**
  2485. * iommu_put_resv_regions - release reserved regions
  2486. * @dev: device for which to free reserved regions
  2487. * @list: reserved region list for device
  2488. *
  2489. * This releases a reserved region list acquired by iommu_get_resv_regions().
  2490. */
  2491. void iommu_put_resv_regions(struct device *dev, struct list_head *list)
  2492. {
  2493. struct iommu_resv_region *entry, *next;
  2494. list_for_each_entry_safe(entry, next, list, list) {
  2495. if (entry->free)
  2496. entry->free(dev, entry);
  2497. else
  2498. kfree(entry);
  2499. }
  2500. }
  2501. EXPORT_SYMBOL(iommu_put_resv_regions);
  2502. struct iommu_resv_region *iommu_alloc_resv_region(phys_addr_t start,
  2503. size_t length, int prot,
  2504. enum iommu_resv_type type,
  2505. gfp_t gfp)
  2506. {
  2507. struct iommu_resv_region *region;
  2508. region = kzalloc_obj(*region, gfp);
  2509. if (!region)
  2510. return NULL;
  2511. INIT_LIST_HEAD(&region->list);
  2512. region->start = start;
  2513. region->length = length;
  2514. region->prot = prot;
  2515. region->type = type;
  2516. return region;
  2517. }
  2518. EXPORT_SYMBOL_GPL(iommu_alloc_resv_region);
  2519. void iommu_set_default_passthrough(bool cmd_line)
  2520. {
  2521. if (cmd_line)
  2522. iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
  2523. iommu_def_domain_type = IOMMU_DOMAIN_IDENTITY;
  2524. }
  2525. void iommu_set_default_translated(bool cmd_line)
  2526. {
  2527. if (cmd_line)
  2528. iommu_cmd_line |= IOMMU_CMD_LINE_DMA_API;
  2529. iommu_def_domain_type = IOMMU_DOMAIN_DMA;
  2530. }
  2531. bool iommu_default_passthrough(void)
  2532. {
  2533. return iommu_def_domain_type == IOMMU_DOMAIN_IDENTITY;
  2534. }
  2535. EXPORT_SYMBOL_GPL(iommu_default_passthrough);
  2536. static const struct iommu_device *iommu_from_fwnode(const struct fwnode_handle *fwnode)
  2537. {
  2538. const struct iommu_device *iommu, *ret = NULL;
  2539. spin_lock(&iommu_device_lock);
  2540. list_for_each_entry(iommu, &iommu_device_list, list)
  2541. if (iommu->fwnode == fwnode) {
  2542. ret = iommu;
  2543. break;
  2544. }
  2545. spin_unlock(&iommu_device_lock);
  2546. return ret;
  2547. }
  2548. const struct iommu_ops *iommu_ops_from_fwnode(const struct fwnode_handle *fwnode)
  2549. {
  2550. const struct iommu_device *iommu = iommu_from_fwnode(fwnode);
  2551. return iommu ? iommu->ops : NULL;
  2552. }
  2553. int iommu_fwspec_init(struct device *dev, struct fwnode_handle *iommu_fwnode)
  2554. {
  2555. const struct iommu_device *iommu = iommu_from_fwnode(iommu_fwnode);
  2556. struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
  2557. if (!iommu)
  2558. return driver_deferred_probe_check_state(dev);
  2559. if (!dev->iommu && !READ_ONCE(iommu->ready))
  2560. return -EPROBE_DEFER;
  2561. if (fwspec)
  2562. return iommu->ops == iommu_fwspec_ops(fwspec) ? 0 : -EINVAL;
  2563. if (!dev_iommu_get(dev))
  2564. return -ENOMEM;
  2565. /* Preallocate for the overwhelmingly common case of 1 ID */
  2566. fwspec = kzalloc_flex(*fwspec, ids, 1);
  2567. if (!fwspec)
  2568. return -ENOMEM;
  2569. fwnode_handle_get(iommu_fwnode);
  2570. fwspec->iommu_fwnode = iommu_fwnode;
  2571. dev_iommu_fwspec_set(dev, fwspec);
  2572. return 0;
  2573. }
  2574. EXPORT_SYMBOL_GPL(iommu_fwspec_init);
  2575. void iommu_fwspec_free(struct device *dev)
  2576. {
  2577. struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
  2578. if (fwspec) {
  2579. fwnode_handle_put(fwspec->iommu_fwnode);
  2580. kfree(fwspec);
  2581. dev_iommu_fwspec_set(dev, NULL);
  2582. }
  2583. }
  2584. int iommu_fwspec_add_ids(struct device *dev, const u32 *ids, int num_ids)
  2585. {
  2586. struct iommu_fwspec *fwspec = dev_iommu_fwspec_get(dev);
  2587. int i, new_num;
  2588. if (!fwspec)
  2589. return -EINVAL;
  2590. new_num = fwspec->num_ids + num_ids;
  2591. if (new_num > 1) {
  2592. fwspec = krealloc(fwspec, struct_size(fwspec, ids, new_num),
  2593. GFP_KERNEL);
  2594. if (!fwspec)
  2595. return -ENOMEM;
  2596. dev_iommu_fwspec_set(dev, fwspec);
  2597. }
  2598. for (i = 0; i < num_ids; i++)
  2599. fwspec->ids[fwspec->num_ids + i] = ids[i];
  2600. fwspec->num_ids = new_num;
  2601. return 0;
  2602. }
  2603. EXPORT_SYMBOL_GPL(iommu_fwspec_add_ids);
  2604. /**
  2605. * iommu_setup_default_domain - Set the default_domain for the group
  2606. * @group: Group to change
  2607. * @target_type: Domain type to set as the default_domain
  2608. *
  2609. * Allocate a default domain and set it as the current domain on the group. If
  2610. * the group already has a default domain it will be changed to the target_type.
  2611. * When target_type is 0 the default domain is selected based on driver and
  2612. * system preferences.
  2613. */
  2614. static int iommu_setup_default_domain(struct iommu_group *group,
  2615. int target_type)
  2616. {
  2617. struct iommu_domain *old_dom = group->default_domain;
  2618. struct group_device *gdev;
  2619. struct iommu_domain *dom;
  2620. bool direct_failed;
  2621. int req_type;
  2622. int ret;
  2623. lockdep_assert_held(&group->mutex);
  2624. req_type = iommu_get_default_domain_type(group, target_type);
  2625. if (req_type < 0)
  2626. return -EINVAL;
  2627. dom = iommu_group_alloc_default_domain(group, req_type);
  2628. if (IS_ERR(dom))
  2629. return PTR_ERR(dom);
  2630. if (group->default_domain == dom)
  2631. return 0;
  2632. if (iommu_is_dma_domain(dom)) {
  2633. ret = iommu_get_dma_cookie(dom);
  2634. if (ret) {
  2635. iommu_domain_free(dom);
  2636. return ret;
  2637. }
  2638. }
  2639. /*
  2640. * IOMMU_RESV_DIRECT and IOMMU_RESV_DIRECT_RELAXABLE regions must be
  2641. * mapped before their device is attached, in order to guarantee
  2642. * continuity with any FW activity
  2643. */
  2644. direct_failed = false;
  2645. for_each_group_device(group, gdev) {
  2646. if (iommu_create_device_direct_mappings(dom, gdev->dev)) {
  2647. direct_failed = true;
  2648. dev_warn_once(
  2649. gdev->dev->iommu->iommu_dev->dev,
  2650. "IOMMU driver was not able to establish FW requested direct mapping.");
  2651. }
  2652. }
  2653. /* We must set default_domain early for __iommu_device_set_domain */
  2654. group->default_domain = dom;
  2655. if (!group->domain) {
  2656. /*
  2657. * Drivers are not allowed to fail the first domain attach.
  2658. * The only way to recover from this is to fail attaching the
  2659. * iommu driver and call ops->release_device. Put the domain
  2660. * in group->default_domain so it is freed after.
  2661. */
  2662. ret = __iommu_group_set_domain_internal(
  2663. group, dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
  2664. if (WARN_ON(ret))
  2665. goto out_free_old;
  2666. } else {
  2667. ret = __iommu_group_set_domain(group, dom);
  2668. if (ret)
  2669. goto err_restore_def_domain;
  2670. }
  2671. /*
  2672. * Drivers are supposed to allow mappings to be installed in a domain
  2673. * before device attachment, but some don't. Hack around this defect by
  2674. * trying again after attaching. If this happens it means the device
  2675. * will not continuously have the IOMMU_RESV_DIRECT map.
  2676. */
  2677. if (direct_failed) {
  2678. for_each_group_device(group, gdev) {
  2679. ret = iommu_create_device_direct_mappings(dom, gdev->dev);
  2680. if (ret)
  2681. goto err_restore_domain;
  2682. }
  2683. }
  2684. out_free_old:
  2685. if (old_dom)
  2686. iommu_domain_free(old_dom);
  2687. return ret;
  2688. err_restore_domain:
  2689. if (old_dom)
  2690. __iommu_group_set_domain_internal(
  2691. group, old_dom, IOMMU_SET_DOMAIN_MUST_SUCCEED);
  2692. err_restore_def_domain:
  2693. if (old_dom) {
  2694. iommu_domain_free(dom);
  2695. group->default_domain = old_dom;
  2696. }
  2697. return ret;
  2698. }
  2699. /*
  2700. * Changing the default domain through sysfs requires the users to unbind the
  2701. * drivers from the devices in the iommu group, except for a DMA -> DMA-FQ
  2702. * transition. Return failure if this isn't met.
  2703. *
  2704. * We need to consider the race between this and the device release path.
  2705. * group->mutex is used here to guarantee that the device release path
  2706. * will not be entered at the same time.
  2707. */
  2708. static ssize_t iommu_group_store_type(struct iommu_group *group,
  2709. const char *buf, size_t count)
  2710. {
  2711. struct group_device *gdev;
  2712. int ret, req_type;
  2713. if (!capable(CAP_SYS_ADMIN) || !capable(CAP_SYS_RAWIO))
  2714. return -EACCES;
  2715. if (WARN_ON(!group) || !group->default_domain)
  2716. return -EINVAL;
  2717. if (sysfs_streq(buf, "identity"))
  2718. req_type = IOMMU_DOMAIN_IDENTITY;
  2719. else if (sysfs_streq(buf, "DMA"))
  2720. req_type = IOMMU_DOMAIN_DMA;
  2721. else if (sysfs_streq(buf, "DMA-FQ"))
  2722. req_type = IOMMU_DOMAIN_DMA_FQ;
  2723. else if (sysfs_streq(buf, "auto"))
  2724. req_type = 0;
  2725. else
  2726. return -EINVAL;
  2727. mutex_lock(&group->mutex);
  2728. /* We can bring up a flush queue without tearing down the domain. */
  2729. if (req_type == IOMMU_DOMAIN_DMA_FQ &&
  2730. group->default_domain->type == IOMMU_DOMAIN_DMA) {
  2731. ret = iommu_dma_init_fq(group->default_domain);
  2732. if (ret)
  2733. goto out_unlock;
  2734. group->default_domain->type = IOMMU_DOMAIN_DMA_FQ;
  2735. ret = count;
  2736. goto out_unlock;
  2737. }
  2738. /* Otherwise, ensure that device exists and no driver is bound. */
  2739. if (list_empty(&group->devices) || group->owner_cnt) {
  2740. ret = -EPERM;
  2741. goto out_unlock;
  2742. }
  2743. ret = iommu_setup_default_domain(group, req_type);
  2744. if (ret)
  2745. goto out_unlock;
  2746. /* Make sure dma_ops is appropriatley set */
  2747. for_each_group_device(group, gdev)
  2748. iommu_setup_dma_ops(gdev->dev, group->default_domain);
  2749. out_unlock:
  2750. mutex_unlock(&group->mutex);
  2751. return ret ?: count;
  2752. }
  2753. /**
  2754. * iommu_device_use_default_domain() - Device driver wants to handle device
  2755. * DMA through the kernel DMA API.
  2756. * @dev: The device.
  2757. *
  2758. * The device driver about to bind @dev wants to do DMA through the kernel
  2759. * DMA API. Return 0 if it is allowed, otherwise an error.
  2760. */
  2761. int iommu_device_use_default_domain(struct device *dev)
  2762. {
  2763. /* Caller is the driver core during the pre-probe path */
  2764. struct iommu_group *group = dev->iommu_group;
  2765. int ret = 0;
  2766. if (!group)
  2767. return 0;
  2768. mutex_lock(&group->mutex);
  2769. /* We may race against bus_iommu_probe() finalising groups here */
  2770. if (!group->default_domain) {
  2771. ret = -EPROBE_DEFER;
  2772. goto unlock_out;
  2773. }
  2774. if (group->owner_cnt) {
  2775. if (group->domain != group->default_domain || group->owner ||
  2776. !xa_empty(&group->pasid_array)) {
  2777. ret = -EBUSY;
  2778. goto unlock_out;
  2779. }
  2780. }
  2781. group->owner_cnt++;
  2782. unlock_out:
  2783. mutex_unlock(&group->mutex);
  2784. return ret;
  2785. }
  2786. /**
  2787. * iommu_device_unuse_default_domain() - Device driver stops handling device
  2788. * DMA through the kernel DMA API.
  2789. * @dev: The device.
  2790. *
  2791. * The device driver doesn't want to do DMA through kernel DMA API anymore.
  2792. * It must be called after iommu_device_use_default_domain().
  2793. */
  2794. void iommu_device_unuse_default_domain(struct device *dev)
  2795. {
  2796. /* Caller is the driver core during the post-probe path */
  2797. struct iommu_group *group = dev->iommu_group;
  2798. if (!group)
  2799. return;
  2800. mutex_lock(&group->mutex);
  2801. if (!WARN_ON(!group->owner_cnt || !xa_empty(&group->pasid_array)))
  2802. group->owner_cnt--;
  2803. mutex_unlock(&group->mutex);
  2804. }
  2805. static int __iommu_group_alloc_blocking_domain(struct iommu_group *group)
  2806. {
  2807. struct device *dev = iommu_group_first_dev(group);
  2808. const struct iommu_ops *ops = dev_iommu_ops(dev);
  2809. struct iommu_domain *domain;
  2810. if (group->blocking_domain)
  2811. return 0;
  2812. if (ops->blocked_domain) {
  2813. group->blocking_domain = ops->blocked_domain;
  2814. return 0;
  2815. }
  2816. /*
  2817. * For drivers that do not yet understand IOMMU_DOMAIN_BLOCKED create an
  2818. * empty PAGING domain instead.
  2819. */
  2820. domain = iommu_paging_domain_alloc(dev);
  2821. if (IS_ERR(domain))
  2822. return PTR_ERR(domain);
  2823. group->blocking_domain = domain;
  2824. return 0;
  2825. }
  2826. static int __iommu_take_dma_ownership(struct iommu_group *group, void *owner)
  2827. {
  2828. int ret;
  2829. if ((group->domain && group->domain != group->default_domain) ||
  2830. !xa_empty(&group->pasid_array))
  2831. return -EBUSY;
  2832. ret = __iommu_group_alloc_blocking_domain(group);
  2833. if (ret)
  2834. return ret;
  2835. ret = __iommu_group_set_domain(group, group->blocking_domain);
  2836. if (ret)
  2837. return ret;
  2838. group->owner = owner;
  2839. group->owner_cnt++;
  2840. return 0;
  2841. }
  2842. /**
  2843. * iommu_group_claim_dma_owner() - Set DMA ownership of a group
  2844. * @group: The group.
  2845. * @owner: Caller specified pointer. Used for exclusive ownership.
  2846. *
  2847. * This is to support backward compatibility for vfio which manages the dma
  2848. * ownership in iommu_group level. New invocations on this interface should be
  2849. * prohibited. Only a single owner may exist for a group.
  2850. */
  2851. int iommu_group_claim_dma_owner(struct iommu_group *group, void *owner)
  2852. {
  2853. int ret = 0;
  2854. if (WARN_ON(!owner))
  2855. return -EINVAL;
  2856. mutex_lock(&group->mutex);
  2857. if (group->owner_cnt) {
  2858. ret = -EPERM;
  2859. goto unlock_out;
  2860. }
  2861. ret = __iommu_take_dma_ownership(group, owner);
  2862. unlock_out:
  2863. mutex_unlock(&group->mutex);
  2864. return ret;
  2865. }
  2866. EXPORT_SYMBOL_GPL(iommu_group_claim_dma_owner);
  2867. /**
  2868. * iommu_device_claim_dma_owner() - Set DMA ownership of a device
  2869. * @dev: The device.
  2870. * @owner: Caller specified pointer. Used for exclusive ownership.
  2871. *
  2872. * Claim the DMA ownership of a device. Multiple devices in the same group may
  2873. * concurrently claim ownership if they present the same owner value. Returns 0
  2874. * on success and error code on failure
  2875. */
  2876. int iommu_device_claim_dma_owner(struct device *dev, void *owner)
  2877. {
  2878. /* Caller must be a probed driver on dev */
  2879. struct iommu_group *group = dev->iommu_group;
  2880. int ret = 0;
  2881. if (WARN_ON(!owner))
  2882. return -EINVAL;
  2883. if (!group)
  2884. return -ENODEV;
  2885. mutex_lock(&group->mutex);
  2886. if (group->owner_cnt) {
  2887. if (group->owner != owner) {
  2888. ret = -EPERM;
  2889. goto unlock_out;
  2890. }
  2891. group->owner_cnt++;
  2892. goto unlock_out;
  2893. }
  2894. ret = __iommu_take_dma_ownership(group, owner);
  2895. unlock_out:
  2896. mutex_unlock(&group->mutex);
  2897. return ret;
  2898. }
  2899. EXPORT_SYMBOL_GPL(iommu_device_claim_dma_owner);
  2900. static void __iommu_release_dma_ownership(struct iommu_group *group)
  2901. {
  2902. if (WARN_ON(!group->owner_cnt || !group->owner ||
  2903. !xa_empty(&group->pasid_array)))
  2904. return;
  2905. group->owner_cnt = 0;
  2906. group->owner = NULL;
  2907. __iommu_group_set_domain_nofail(group, group->default_domain);
  2908. }
  2909. /**
  2910. * iommu_group_release_dma_owner() - Release DMA ownership of a group
  2911. * @group: The group
  2912. *
  2913. * Release the DMA ownership claimed by iommu_group_claim_dma_owner().
  2914. */
  2915. void iommu_group_release_dma_owner(struct iommu_group *group)
  2916. {
  2917. mutex_lock(&group->mutex);
  2918. __iommu_release_dma_ownership(group);
  2919. mutex_unlock(&group->mutex);
  2920. }
  2921. EXPORT_SYMBOL_GPL(iommu_group_release_dma_owner);
  2922. /**
  2923. * iommu_device_release_dma_owner() - Release DMA ownership of a device
  2924. * @dev: The device.
  2925. *
  2926. * Release the DMA ownership claimed by iommu_device_claim_dma_owner().
  2927. */
  2928. void iommu_device_release_dma_owner(struct device *dev)
  2929. {
  2930. /* Caller must be a probed driver on dev */
  2931. struct iommu_group *group = dev->iommu_group;
  2932. mutex_lock(&group->mutex);
  2933. if (group->owner_cnt > 1)
  2934. group->owner_cnt--;
  2935. else
  2936. __iommu_release_dma_ownership(group);
  2937. mutex_unlock(&group->mutex);
  2938. }
  2939. EXPORT_SYMBOL_GPL(iommu_device_release_dma_owner);
  2940. /**
  2941. * iommu_group_dma_owner_claimed() - Query group dma ownership status
  2942. * @group: The group.
  2943. *
  2944. * This provides status query on a given group. It is racy and only for
  2945. * non-binding status reporting.
  2946. */
  2947. bool iommu_group_dma_owner_claimed(struct iommu_group *group)
  2948. {
  2949. unsigned int user;
  2950. mutex_lock(&group->mutex);
  2951. user = group->owner_cnt;
  2952. mutex_unlock(&group->mutex);
  2953. return user;
  2954. }
  2955. EXPORT_SYMBOL_GPL(iommu_group_dma_owner_claimed);
  2956. static void iommu_remove_dev_pasid(struct device *dev, ioasid_t pasid,
  2957. struct iommu_domain *domain)
  2958. {
  2959. const struct iommu_ops *ops = dev_iommu_ops(dev);
  2960. struct iommu_domain *blocked_domain = ops->blocked_domain;
  2961. WARN_ON(blocked_domain->ops->set_dev_pasid(blocked_domain,
  2962. dev, pasid, domain));
  2963. }
  2964. static int __iommu_set_group_pasid(struct iommu_domain *domain,
  2965. struct iommu_group *group, ioasid_t pasid,
  2966. struct iommu_domain *old)
  2967. {
  2968. struct group_device *device, *last_gdev;
  2969. int ret;
  2970. for_each_group_device(group, device) {
  2971. if (device->dev->iommu->max_pasids > 0) {
  2972. ret = domain->ops->set_dev_pasid(domain, device->dev,
  2973. pasid, old);
  2974. if (ret)
  2975. goto err_revert;
  2976. }
  2977. }
  2978. return 0;
  2979. err_revert:
  2980. last_gdev = device;
  2981. for_each_group_device(group, device) {
  2982. if (device == last_gdev)
  2983. break;
  2984. if (device->dev->iommu->max_pasids > 0) {
  2985. /*
  2986. * If no old domain, undo the succeeded devices/pasid.
  2987. * Otherwise, rollback the succeeded devices/pasid to
  2988. * the old domain. And it is a driver bug to fail
  2989. * attaching with a previously good domain.
  2990. */
  2991. if (!old ||
  2992. WARN_ON(old->ops->set_dev_pasid(old, device->dev,
  2993. pasid, domain)))
  2994. iommu_remove_dev_pasid(device->dev, pasid, domain);
  2995. }
  2996. }
  2997. return ret;
  2998. }
  2999. static void __iommu_remove_group_pasid(struct iommu_group *group,
  3000. ioasid_t pasid,
  3001. struct iommu_domain *domain)
  3002. {
  3003. struct group_device *device;
  3004. for_each_group_device(group, device) {
  3005. if (device->dev->iommu->max_pasids > 0)
  3006. iommu_remove_dev_pasid(device->dev, pasid, domain);
  3007. }
  3008. }
  3009. /*
  3010. * iommu_attach_device_pasid() - Attach a domain to pasid of device
  3011. * @domain: the iommu domain.
  3012. * @dev: the attached device.
  3013. * @pasid: the pasid of the device.
  3014. * @handle: the attach handle.
  3015. *
  3016. * Caller should always provide a new handle to avoid race with the paths
  3017. * that have lockless reference to handle if it intends to pass a valid handle.
  3018. *
  3019. * Return: 0 on success, or an error.
  3020. */
  3021. int iommu_attach_device_pasid(struct iommu_domain *domain,
  3022. struct device *dev, ioasid_t pasid,
  3023. struct iommu_attach_handle *handle)
  3024. {
  3025. /* Caller must be a probed driver on dev */
  3026. struct iommu_group *group = dev->iommu_group;
  3027. struct group_device *device;
  3028. const struct iommu_ops *ops;
  3029. void *entry;
  3030. int ret;
  3031. if (!group)
  3032. return -ENODEV;
  3033. ops = dev_iommu_ops(dev);
  3034. if (!domain->ops->set_dev_pasid ||
  3035. !ops->blocked_domain ||
  3036. !ops->blocked_domain->ops->set_dev_pasid)
  3037. return -EOPNOTSUPP;
  3038. if (!domain_iommu_ops_compatible(ops, domain) ||
  3039. pasid == IOMMU_NO_PASID)
  3040. return -EINVAL;
  3041. mutex_lock(&group->mutex);
  3042. /*
  3043. * This is a concurrent attach during a device reset. Reject it until
  3044. * pci_dev_reset_iommu_done() attaches the device to group->domain.
  3045. */
  3046. if (group->resetting_domain) {
  3047. ret = -EBUSY;
  3048. goto out_unlock;
  3049. }
  3050. for_each_group_device(group, device) {
  3051. /*
  3052. * Skip PASID validation for devices without PASID support
  3053. * (max_pasids = 0). These devices cannot issue transactions
  3054. * with PASID, so they don't affect group's PASID usage.
  3055. */
  3056. if ((device->dev->iommu->max_pasids > 0) &&
  3057. (pasid >= device->dev->iommu->max_pasids)) {
  3058. ret = -EINVAL;
  3059. goto out_unlock;
  3060. }
  3061. }
  3062. entry = iommu_make_pasid_array_entry(domain, handle);
  3063. /*
  3064. * Entry present is a failure case. Use xa_insert() instead of
  3065. * xa_reserve().
  3066. */
  3067. ret = xa_insert(&group->pasid_array, pasid, XA_ZERO_ENTRY, GFP_KERNEL);
  3068. if (ret)
  3069. goto out_unlock;
  3070. ret = __iommu_set_group_pasid(domain, group, pasid, NULL);
  3071. if (ret) {
  3072. xa_release(&group->pasid_array, pasid);
  3073. goto out_unlock;
  3074. }
  3075. /*
  3076. * The xa_insert() above reserved the memory, and the group->mutex is
  3077. * held, this cannot fail. The new domain cannot be visible until the
  3078. * operation succeeds as we cannot tolerate PRIs becoming concurrently
  3079. * queued and then failing attach.
  3080. */
  3081. WARN_ON(xa_is_err(xa_store(&group->pasid_array,
  3082. pasid, entry, GFP_KERNEL)));
  3083. out_unlock:
  3084. mutex_unlock(&group->mutex);
  3085. return ret;
  3086. }
  3087. EXPORT_SYMBOL_GPL(iommu_attach_device_pasid);
  3088. /**
  3089. * iommu_replace_device_pasid - Replace the domain that a specific pasid
  3090. * of the device is attached to
  3091. * @domain: the new iommu domain
  3092. * @dev: the attached device.
  3093. * @pasid: the pasid of the device.
  3094. * @handle: the attach handle.
  3095. *
  3096. * This API allows the pasid to switch domains. The @pasid should have been
  3097. * attached. Otherwise, this fails. The pasid will keep the old configuration
  3098. * if replacement failed.
  3099. *
  3100. * Caller should always provide a new handle to avoid race with the paths
  3101. * that have lockless reference to handle if it intends to pass a valid handle.
  3102. *
  3103. * Return 0 on success, or an error.
  3104. */
  3105. int iommu_replace_device_pasid(struct iommu_domain *domain,
  3106. struct device *dev, ioasid_t pasid,
  3107. struct iommu_attach_handle *handle)
  3108. {
  3109. /* Caller must be a probed driver on dev */
  3110. struct iommu_group *group = dev->iommu_group;
  3111. struct iommu_attach_handle *entry;
  3112. struct iommu_domain *curr_domain;
  3113. void *curr;
  3114. int ret;
  3115. if (!group)
  3116. return -ENODEV;
  3117. if (!domain->ops->set_dev_pasid)
  3118. return -EOPNOTSUPP;
  3119. if (!domain_iommu_ops_compatible(dev_iommu_ops(dev), domain) ||
  3120. pasid == IOMMU_NO_PASID || !handle)
  3121. return -EINVAL;
  3122. mutex_lock(&group->mutex);
  3123. /*
  3124. * This is a concurrent attach during a device reset. Reject it until
  3125. * pci_dev_reset_iommu_done() attaches the device to group->domain.
  3126. */
  3127. if (group->resetting_domain) {
  3128. ret = -EBUSY;
  3129. goto out_unlock;
  3130. }
  3131. entry = iommu_make_pasid_array_entry(domain, handle);
  3132. curr = xa_cmpxchg(&group->pasid_array, pasid, NULL,
  3133. XA_ZERO_ENTRY, GFP_KERNEL);
  3134. if (xa_is_err(curr)) {
  3135. ret = xa_err(curr);
  3136. goto out_unlock;
  3137. }
  3138. /*
  3139. * No domain (with or without handle) attached, hence not
  3140. * a replace case.
  3141. */
  3142. if (!curr) {
  3143. xa_release(&group->pasid_array, pasid);
  3144. ret = -EINVAL;
  3145. goto out_unlock;
  3146. }
  3147. /*
  3148. * Reusing handle is problematic as there are paths that refers
  3149. * the handle without lock. To avoid race, reject the callers that
  3150. * attempt it.
  3151. */
  3152. if (curr == entry) {
  3153. WARN_ON(1);
  3154. ret = -EINVAL;
  3155. goto out_unlock;
  3156. }
  3157. curr_domain = pasid_array_entry_to_domain(curr);
  3158. ret = 0;
  3159. if (curr_domain != domain) {
  3160. ret = __iommu_set_group_pasid(domain, group,
  3161. pasid, curr_domain);
  3162. if (ret)
  3163. goto out_unlock;
  3164. }
  3165. /*
  3166. * The above xa_cmpxchg() reserved the memory, and the
  3167. * group->mutex is held, this cannot fail.
  3168. */
  3169. WARN_ON(xa_is_err(xa_store(&group->pasid_array,
  3170. pasid, entry, GFP_KERNEL)));
  3171. out_unlock:
  3172. mutex_unlock(&group->mutex);
  3173. return ret;
  3174. }
  3175. EXPORT_SYMBOL_NS_GPL(iommu_replace_device_pasid, "IOMMUFD_INTERNAL");
  3176. /*
  3177. * iommu_detach_device_pasid() - Detach the domain from pasid of device
  3178. * @domain: the iommu domain.
  3179. * @dev: the attached device.
  3180. * @pasid: the pasid of the device.
  3181. *
  3182. * The @domain must have been attached to @pasid of the @dev with
  3183. * iommu_attach_device_pasid().
  3184. */
  3185. void iommu_detach_device_pasid(struct iommu_domain *domain, struct device *dev,
  3186. ioasid_t pasid)
  3187. {
  3188. /* Caller must be a probed driver on dev */
  3189. struct iommu_group *group = dev->iommu_group;
  3190. mutex_lock(&group->mutex);
  3191. __iommu_remove_group_pasid(group, pasid, domain);
  3192. xa_erase(&group->pasid_array, pasid);
  3193. mutex_unlock(&group->mutex);
  3194. }
  3195. EXPORT_SYMBOL_GPL(iommu_detach_device_pasid);
  3196. ioasid_t iommu_alloc_global_pasid(struct device *dev)
  3197. {
  3198. int ret;
  3199. /* max_pasids == 0 means that the device does not support PASID */
  3200. if (!dev->iommu->max_pasids)
  3201. return IOMMU_PASID_INVALID;
  3202. /*
  3203. * max_pasids is set up by vendor driver based on number of PASID bits
  3204. * supported but the IDA allocation is inclusive.
  3205. */
  3206. ret = ida_alloc_range(&iommu_global_pasid_ida, IOMMU_FIRST_GLOBAL_PASID,
  3207. dev->iommu->max_pasids - 1, GFP_KERNEL);
  3208. return ret < 0 ? IOMMU_PASID_INVALID : ret;
  3209. }
  3210. EXPORT_SYMBOL_GPL(iommu_alloc_global_pasid);
  3211. void iommu_free_global_pasid(ioasid_t pasid)
  3212. {
  3213. if (WARN_ON(pasid == IOMMU_PASID_INVALID))
  3214. return;
  3215. ida_free(&iommu_global_pasid_ida, pasid);
  3216. }
  3217. EXPORT_SYMBOL_GPL(iommu_free_global_pasid);
  3218. /**
  3219. * iommu_attach_handle_get - Return the attach handle
  3220. * @group: the iommu group that domain was attached to
  3221. * @pasid: the pasid within the group
  3222. * @type: matched domain type, 0 for any match
  3223. *
  3224. * Return handle or ERR_PTR(-ENOENT) on none, ERR_PTR(-EBUSY) on mismatch.
  3225. *
  3226. * Return the attach handle to the caller. The life cycle of an iommu attach
  3227. * handle is from the time when the domain is attached to the time when the
  3228. * domain is detached. Callers are required to synchronize the call of
  3229. * iommu_attach_handle_get() with domain attachment and detachment. The attach
  3230. * handle can only be used during its life cycle.
  3231. */
  3232. struct iommu_attach_handle *
  3233. iommu_attach_handle_get(struct iommu_group *group, ioasid_t pasid, unsigned int type)
  3234. {
  3235. struct iommu_attach_handle *handle;
  3236. void *entry;
  3237. xa_lock(&group->pasid_array);
  3238. entry = xa_load(&group->pasid_array, pasid);
  3239. if (!entry || xa_pointer_tag(entry) != IOMMU_PASID_ARRAY_HANDLE) {
  3240. handle = ERR_PTR(-ENOENT);
  3241. } else {
  3242. handle = xa_untag_pointer(entry);
  3243. if (type && handle->domain->type != type)
  3244. handle = ERR_PTR(-EBUSY);
  3245. }
  3246. xa_unlock(&group->pasid_array);
  3247. return handle;
  3248. }
  3249. EXPORT_SYMBOL_NS_GPL(iommu_attach_handle_get, "IOMMUFD_INTERNAL");
  3250. /**
  3251. * iommu_attach_group_handle - Attach an IOMMU domain to an IOMMU group
  3252. * @domain: IOMMU domain to attach
  3253. * @group: IOMMU group that will be attached
  3254. * @handle: attach handle
  3255. *
  3256. * Returns 0 on success and error code on failure.
  3257. *
  3258. * This is a variant of iommu_attach_group(). It allows the caller to provide
  3259. * an attach handle and use it when the domain is attached. This is currently
  3260. * used by IOMMUFD to deliver the I/O page faults.
  3261. *
  3262. * Caller should always provide a new handle to avoid race with the paths
  3263. * that have lockless reference to handle.
  3264. */
  3265. int iommu_attach_group_handle(struct iommu_domain *domain,
  3266. struct iommu_group *group,
  3267. struct iommu_attach_handle *handle)
  3268. {
  3269. void *entry;
  3270. int ret;
  3271. if (!handle)
  3272. return -EINVAL;
  3273. mutex_lock(&group->mutex);
  3274. entry = iommu_make_pasid_array_entry(domain, handle);
  3275. ret = xa_insert(&group->pasid_array,
  3276. IOMMU_NO_PASID, XA_ZERO_ENTRY, GFP_KERNEL);
  3277. if (ret)
  3278. goto out_unlock;
  3279. ret = __iommu_attach_group(domain, group);
  3280. if (ret) {
  3281. xa_release(&group->pasid_array, IOMMU_NO_PASID);
  3282. goto out_unlock;
  3283. }
  3284. /*
  3285. * The xa_insert() above reserved the memory, and the group->mutex is
  3286. * held, this cannot fail. The new domain cannot be visible until the
  3287. * operation succeeds as we cannot tolerate PRIs becoming concurrently
  3288. * queued and then failing attach.
  3289. */
  3290. WARN_ON(xa_is_err(xa_store(&group->pasid_array,
  3291. IOMMU_NO_PASID, entry, GFP_KERNEL)));
  3292. out_unlock:
  3293. mutex_unlock(&group->mutex);
  3294. return ret;
  3295. }
  3296. EXPORT_SYMBOL_NS_GPL(iommu_attach_group_handle, "IOMMUFD_INTERNAL");
  3297. /**
  3298. * iommu_detach_group_handle - Detach an IOMMU domain from an IOMMU group
  3299. * @domain: IOMMU domain to attach
  3300. * @group: IOMMU group that will be attached
  3301. *
  3302. * Detach the specified IOMMU domain from the specified IOMMU group.
  3303. * It must be used in conjunction with iommu_attach_group_handle().
  3304. */
  3305. void iommu_detach_group_handle(struct iommu_domain *domain,
  3306. struct iommu_group *group)
  3307. {
  3308. mutex_lock(&group->mutex);
  3309. __iommu_group_set_core_domain(group);
  3310. xa_erase(&group->pasid_array, IOMMU_NO_PASID);
  3311. mutex_unlock(&group->mutex);
  3312. }
  3313. EXPORT_SYMBOL_NS_GPL(iommu_detach_group_handle, "IOMMUFD_INTERNAL");
  3314. /**
  3315. * iommu_replace_group_handle - replace the domain that a group is attached to
  3316. * @group: IOMMU group that will be attached to the new domain
  3317. * @new_domain: new IOMMU domain to replace with
  3318. * @handle: attach handle
  3319. *
  3320. * This API allows the group to switch domains without being forced to go to
  3321. * the blocking domain in-between. It allows the caller to provide an attach
  3322. * handle for the new domain and use it when the domain is attached.
  3323. *
  3324. * If the currently attached domain is a core domain (e.g. a default_domain),
  3325. * it will act just like the iommu_attach_group_handle().
  3326. *
  3327. * Caller should always provide a new handle to avoid race with the paths
  3328. * that have lockless reference to handle.
  3329. */
  3330. int iommu_replace_group_handle(struct iommu_group *group,
  3331. struct iommu_domain *new_domain,
  3332. struct iommu_attach_handle *handle)
  3333. {
  3334. void *curr, *entry;
  3335. int ret;
  3336. if (!new_domain || !handle)
  3337. return -EINVAL;
  3338. mutex_lock(&group->mutex);
  3339. entry = iommu_make_pasid_array_entry(new_domain, handle);
  3340. ret = xa_reserve(&group->pasid_array, IOMMU_NO_PASID, GFP_KERNEL);
  3341. if (ret)
  3342. goto err_unlock;
  3343. ret = __iommu_group_set_domain(group, new_domain);
  3344. if (ret)
  3345. goto err_release;
  3346. curr = xa_store(&group->pasid_array, IOMMU_NO_PASID, entry, GFP_KERNEL);
  3347. WARN_ON(xa_is_err(curr));
  3348. mutex_unlock(&group->mutex);
  3349. return 0;
  3350. err_release:
  3351. xa_release(&group->pasid_array, IOMMU_NO_PASID);
  3352. err_unlock:
  3353. mutex_unlock(&group->mutex);
  3354. return ret;
  3355. }
  3356. EXPORT_SYMBOL_NS_GPL(iommu_replace_group_handle, "IOMMUFD_INTERNAL");
  3357. /**
  3358. * pci_dev_reset_iommu_prepare() - Block IOMMU to prepare for a PCI device reset
  3359. * @pdev: PCI device that is going to enter a reset routine
  3360. *
  3361. * The PCIe r6.0, sec 10.3.1 IMPLEMENTATION NOTE recommends to disable and block
  3362. * ATS before initiating a reset. This means that a PCIe device during the reset
  3363. * routine wants to block any IOMMU activity: translation and ATS invalidation.
  3364. *
  3365. * This function attaches the device's RID/PASID(s) the group->blocking_domain,
  3366. * setting the group->resetting_domain. This allows the IOMMU driver pausing any
  3367. * IOMMU activity while leaving the group->domain pointer intact. Later when the
  3368. * reset is finished, pci_dev_reset_iommu_done() can restore everything.
  3369. *
  3370. * Caller must use pci_dev_reset_iommu_prepare() with pci_dev_reset_iommu_done()
  3371. * before/after the core-level reset routine, to unset the resetting_domain.
  3372. *
  3373. * Return: 0 on success or negative error code if the preparation failed.
  3374. *
  3375. * These two functions are designed to be used by PCI reset functions that would
  3376. * not invoke any racy iommu_release_device(), since PCI sysfs node gets removed
  3377. * before it notifies with a BUS_NOTIFY_REMOVED_DEVICE. When using them in other
  3378. * case, callers must ensure there will be no racy iommu_release_device() call,
  3379. * which otherwise would UAF the dev->iommu_group pointer.
  3380. */
  3381. int pci_dev_reset_iommu_prepare(struct pci_dev *pdev)
  3382. {
  3383. struct iommu_group *group = pdev->dev.iommu_group;
  3384. unsigned long pasid;
  3385. void *entry;
  3386. int ret;
  3387. if (!pci_ats_supported(pdev) || !dev_has_iommu(&pdev->dev))
  3388. return 0;
  3389. guard(mutex)(&group->mutex);
  3390. /* Re-entry is not allowed */
  3391. if (WARN_ON(group->resetting_domain))
  3392. return -EBUSY;
  3393. ret = __iommu_group_alloc_blocking_domain(group);
  3394. if (ret)
  3395. return ret;
  3396. /* Stage RID domain at blocking_domain while retaining group->domain */
  3397. if (group->domain != group->blocking_domain) {
  3398. ret = __iommu_attach_device(group->blocking_domain, &pdev->dev,
  3399. group->domain);
  3400. if (ret)
  3401. return ret;
  3402. }
  3403. /*
  3404. * Stage PASID domains at blocking_domain while retaining pasid_array.
  3405. *
  3406. * The pasid_array is mostly fenced by group->mutex, except one reader
  3407. * in iommu_attach_handle_get(), so it's safe to read without xa_lock.
  3408. */
  3409. xa_for_each_start(&group->pasid_array, pasid, entry, 1)
  3410. iommu_remove_dev_pasid(&pdev->dev, pasid,
  3411. pasid_array_entry_to_domain(entry));
  3412. group->resetting_domain = group->blocking_domain;
  3413. return ret;
  3414. }
  3415. EXPORT_SYMBOL_GPL(pci_dev_reset_iommu_prepare);
  3416. /**
  3417. * pci_dev_reset_iommu_done() - Restore IOMMU after a PCI device reset is done
  3418. * @pdev: PCI device that has finished a reset routine
  3419. *
  3420. * After a PCIe device finishes a reset routine, it wants to restore its IOMMU
  3421. * IOMMU activity, including new translation as well as cache invalidation, by
  3422. * re-attaching all RID/PASID of the device's back to the domains retained in
  3423. * the core-level structure.
  3424. *
  3425. * Caller must pair it with a successful pci_dev_reset_iommu_prepare().
  3426. *
  3427. * Note that, although unlikely, there is a risk that re-attaching domains might
  3428. * fail due to some unexpected happening like OOM.
  3429. */
  3430. void pci_dev_reset_iommu_done(struct pci_dev *pdev)
  3431. {
  3432. struct iommu_group *group = pdev->dev.iommu_group;
  3433. unsigned long pasid;
  3434. void *entry;
  3435. if (!pci_ats_supported(pdev) || !dev_has_iommu(&pdev->dev))
  3436. return;
  3437. guard(mutex)(&group->mutex);
  3438. /* pci_dev_reset_iommu_prepare() was bypassed for the device */
  3439. if (!group->resetting_domain)
  3440. return;
  3441. /* pci_dev_reset_iommu_prepare() was not successfully called */
  3442. if (WARN_ON(!group->blocking_domain))
  3443. return;
  3444. /* Re-attach RID domain back to group->domain */
  3445. if (group->domain != group->blocking_domain) {
  3446. WARN_ON(__iommu_attach_device(group->domain, &pdev->dev,
  3447. group->blocking_domain));
  3448. }
  3449. /*
  3450. * Re-attach PASID domains back to the domains retained in pasid_array.
  3451. *
  3452. * The pasid_array is mostly fenced by group->mutex, except one reader
  3453. * in iommu_attach_handle_get(), so it's safe to read without xa_lock.
  3454. */
  3455. xa_for_each_start(&group->pasid_array, pasid, entry, 1)
  3456. WARN_ON(__iommu_set_group_pasid(
  3457. pasid_array_entry_to_domain(entry), group, pasid,
  3458. group->blocking_domain));
  3459. group->resetting_domain = NULL;
  3460. }
  3461. EXPORT_SYMBOL_GPL(pci_dev_reset_iommu_done);
  3462. #if IS_ENABLED(CONFIG_IRQ_MSI_IOMMU)
  3463. /**
  3464. * iommu_dma_prepare_msi() - Map the MSI page in the IOMMU domain
  3465. * @desc: MSI descriptor, will store the MSI page
  3466. * @msi_addr: MSI target address to be mapped
  3467. *
  3468. * The implementation of sw_msi() should take msi_addr and map it to
  3469. * an IOVA in the domain and call msi_desc_set_iommu_msi_iova() with the
  3470. * mapping information.
  3471. *
  3472. * Return: 0 on success or negative error code if the mapping failed.
  3473. */
  3474. int iommu_dma_prepare_msi(struct msi_desc *desc, phys_addr_t msi_addr)
  3475. {
  3476. struct device *dev = msi_desc_to_dev(desc);
  3477. struct iommu_group *group = dev->iommu_group;
  3478. int ret = 0;
  3479. if (!group)
  3480. return 0;
  3481. mutex_lock(&group->mutex);
  3482. /* An IDENTITY domain must pass through */
  3483. if (group->domain && group->domain->type != IOMMU_DOMAIN_IDENTITY) {
  3484. switch (group->domain->cookie_type) {
  3485. case IOMMU_COOKIE_DMA_MSI:
  3486. case IOMMU_COOKIE_DMA_IOVA:
  3487. ret = iommu_dma_sw_msi(group->domain, desc, msi_addr);
  3488. break;
  3489. case IOMMU_COOKIE_IOMMUFD:
  3490. ret = iommufd_sw_msi(group->domain, desc, msi_addr);
  3491. break;
  3492. default:
  3493. ret = -EOPNOTSUPP;
  3494. break;
  3495. }
  3496. }
  3497. mutex_unlock(&group->mutex);
  3498. return ret;
  3499. }
  3500. #endif /* CONFIG_IRQ_MSI_IOMMU */